What will be the result of compiling and running the following program?.
public class Main { private static String msg(String msg) { System.out.println(msg); return msg; }//from ww w.j a v a2 s . co m public Main() { m = msg("1"); } { m = msg("2"); } String m = msg("3"); public static void main(String[] args) { Object obj = new Main(); } }
Select the one correct answer.
(c)
The program will compile, and print 2, 3, and 1, when run.
When the object is created and initialized, the instance initializer block is executed first, printing 2.
Then the instance initializer expression is executed, printing 3.
Finally, the constructor body is executed, printing 1.
The forward reference in the instance initializer block is legal, as the use of the field m is on the left-hand side of the assignment.