Java OCA OCP Practice Question 1982

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.  ja  v  a 2  s  .com

  static String m = msg("1");

  { m = msg("2"); }

  static { 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.


(e)

Note

The program will compile, and print 1, 3, and 2, when run.

First, the static initializers are executed when the class is initialized, printing 1 and 3.

When the object is created and initialized, the instance initializer block is executed, printing 2.




PreviousNext

Related