JavaSE最容易犯错的知识点、持续更新中~~~

1、变量的先++与后++区别

count++的情况

public class Test01 {
  public static void main(String[] args){
      int count=0;
      int num=0;
      for (int i=0; i<=100; i++){
          num = num+i;
          count = count++;
      }
      System.out.println("num*count = " + num*count);c
  }
}
//运行结果
num*count = 0

对应的class文件如下:

public class Test01 {
    public Test01() {
    }
    public static void main(String[] args) {
        int count = 0;
        int num = 0;

        for(int i = 0; i <= 100; ++i) {
            num += i;
            int var4 = count + 1;
            count = count;
        }
        System.out.println("num*count = " + num * count);
    }
}

++count的情况

public class Test01 {
  public static void main(String[] args){
      int count=0;
      int num=0;
      for (int i=0; i<=100; i++){
          num = num+i;
          count = ++count;
      }
      System.out.println("num*count = " + num*count);  
  }
}
//运行结果
num*count = 510050

对应的class文件如下:

public class Test01 {
    public Test01() {
    }

    public static void main(String[] args) {
        int count = 0;
        int num = 0;

        for(int i = 0; i <= 100; ++i) {
            num += i;
            ++count;
            count = count;
        }
        System.out.println("num*count = " + num * count);
    }
}

总结:count = count++; 编译成class文件后会先+1赋值给一个缓存变量,然后自赋值,这样count的值始终不会变,为初始值。而 count = ++count; 是先自增1,然后赋值给自身,这样值就+1了。

2、静态方法调用问题

先看下面这段代码,乍一看肯定是报空指针异常的:

public class MyApplication {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Test test=null;
        test.hello(); //通过空对象(null)调用

        Test test1=new Test();
        test1.hello(); //通过new的对象调用
    }
}
class Test {
    public static void hello() {
        System.out.println("hello");
    }
}
//输出结果
hello
hello
Test test=null;
test.hello(); 

这种调用并不是我们天真的想的空对象调用会报空指针异常,通过它的编译后的class文件就可以清楚的看出来了:

public class MyApplication {
    public MyApplication() {
    }

    public static void main(String[] args) {
        Test test = null;
        Test.hello();
        Test test1 = new Test();
        Test.hello();
    }
}

从class文件可以得出结论:类中的静态方法的调用始终是通过类名.方法名调用的 ,即使你用对象调用该静态方法,但是 底层JVM 的实现就是通过类名.方法名调用---->无论对象是否为空,都能调用,不会抛出空指针异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值