Java OCA OCP Practice Question 986

Question

What is the result of the following?

1:  public class MyClass { 
2:    static String result = ""; 
3:    { result += "c"; } 
4:    static  //from w  w  w.  j  a  v  a 2s. c o  m
5:    { result += "u"; } 
6:    { result += "r"; } 
7: } 

1: public class Main { 
2:   public static void main(String[] args) { 
3:     System.out.print(MyClass.result + " "); 
4:     System.out.print(MyClass.result + " "); 
5:     new MyClass(); 
6:     new MyClass(); 
7:     System.out.print(MyClass.result + " "); 
8:   } 
9: } 
A.  curur 
B.  ucrcr 
C.  u ucrcr 
D.  u u curcur 
E.  u u ucrcr 
F.  ur ur urc 
G.  The code does not compile. 


E.

Note

On line 3 of Main, we refer to MyClass for the first time.

At this point the statics in MyClass get initialized.

In this case, the statics are the static declaration of result and the static initializer.

result is u at this point.

On line 4, result is the same because the static initialization is only run once.

On line 5, we create a new MyClass, which triggers the instance initializers in the order they appear in the file.

Now result is ucr.

Line 6 creates another MyClass, triggering another set of initializers.

Now result is ucrcr.

Notice how the static is on a different line than the initialization code in lines 4-5 of MyClass.

The exam may try to trick you by formatting the code like this to confuse you.




PreviousNext

Related