Java OCA OCP Practice Question 1980

Question

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.

  • (a) The program will fail to compile.
  • (b) The program will compile, and print 1, 2, and 3, when run.
  • (c) The program will compile, and print 2, 3, and 1, when run.
  • (d) The program will compile, and print 3, 1, and 2, when run.
  • (e) The program will compile, and print 1, 3, and 2, when run.


(c)

Note

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.




PreviousNext

Related