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 的实现就是通过类名.方法名调用---->无论对象是否为空,都能调用,不会抛出空指针异常。
,