代碼如下:
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/