What is the result of the following?
1: public class MyValue { 2: static String result = ""; 3: { result += "CCC"; } 4: static 5: { result += "UUU"; } 6: { result += "RRR"; } 7: } 1: public class Main { 2: public static void main(String[] args) { 3: System.out.print(MyValue.result + " "); 4: System.out.print(MyValue.result + " "); 5: new MyValue(); 6: new MyValue(); 7: System.out.print(MyValue.result + " "); 8: } 9: }
E.
result is a static variable.
static initializer only runs once per class.
The first two
System.out.print(MyValue.result + " "); System.out.print(MyValue.result + " ");
only call static initializer once.
new MyValue(); new MyValue();
calls the instance initializers twice and value is initialized in the order they appear in the file
class MyValue { static String result = ""; { result += "CCC"; } static { result += "UUU"; } { result += "RRR"; } } public class Main { public static void main(String[] args) { System.out.print(MyValue.result + " "); System.out.print(MyValue.result + " "); new MyValue(); new MyValue(); System.out.print(MyValue.result + " "); } }