What is the result of the following?
1: public class MyClass { 2: String value = "t"; 3: { value += "a"; } 4: { value += "c"; } 5: public MyClass() { 6: value += "b"; 7: } // ww w. j a va 2 s .c om 8: public MyClass(String s) { 9: value += s; 10: } 11: public static void main(String[] args) { 12: MyClass order = new MyClass("f"); 13: order = new MyClass(); 14: System.out.println(order.value); 15: } 16:}
A. tacb B. tacf C. tacbf D. tacfb E. tacftacb F. The code does not compile. G. An exception is thrown.
A.
Line 4 instantiates an MyClass.
Java runs the declarations and instance initializers first in the order they appear.
This sets value to tacf
.
Line 5 creates another MyClass and initializes value to tacb
.
The object on line 5 is stored in the same variable line 4 used.
This makes the object created on line 4 unreachable.
When value is printed, it is the instance variable in the object created on line 5.