An interview question for class initialization

What is the output of the following code counter1, counter2, put line 10 after line 12, what is the output of outer1, counter2? Why?

 1 public class Test {
 2     public static void main(String[] args) {
 3         System.out.println(Singleton.counter1);
 4         System.out.println(Singleton.counter2);
 5     }
 6     
 7 }
 8 
 9 class Singleton{
10     private static Singleton singleton = new Singleton();
11     public static int counter1;
12     public static int counter2=0;
13     private Singleton(){
14         counter1++;
15         counter2++;
16     }
17     public static Singleton getInstance(){
18         return singleton;
19     }
20 }

1. counter1=1,counter2=0

  The reason is that in the preparation stage of class initialization, memory will be allocated for static variables and the default initial value will be set. At this time, singleton=null, counter1=0, counter2=0; and then in the initialization stage, the static variable is assigned an initial value, then from Initialize from top to bottom, first new Singleton(), counter1=1, counter2=1, then 11 lines of counter1 are unchanged, and counter2 is reassigned to 0.

2. counter1=1,counter2=1

  The reason is that the code order is changed, and new Singleton() is executed later.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324726177&siteId=291194637