代码如下:
public class jvmtest {
private static int count1;
private static int count2 = 0;
private static jvmtest jvmtest =new jvmtest();
public jvmtest() {
system.out.println("jvmtest");
count1++;
count2++;
}
public static jvmtest getinstance() {
return jvmtest;
public static void main(string[] args) {
system.err.println("count1=" + jvmtest.count1);
system.err.println("count2=" + jvmtest.count2);
这段代码运行之后的结果是什么呢?
如果你已经有答案了,请看下面这段代码:
这段运行结果又是什么呢?
第一段首先count1和count2值都是0,一个是类加载过程中默认的0,一个是赋值为0,然后执行了new操作,对count1和count2进行自加,所以到这里,count1和count2的值都是1.而第二段则是先new操作对count1和count2都自加,变成1,然后再对count2进行赋值操作,所以count2的值又从1改成了0.
最新内容请见作者的github页:http://qaseven.github.io/