Java OCA OCP Practice Question 1530

Question

What will be the result of attempting to compile and run the following class?

public class Main{
   static String s1 = m ("a");{
      s1 = m ("b");
    }//from  ww w.  j  a  v  a 2  s. c  o  m
   static{
      s1 = m ("c");
    }
   public static void main (String args []){
      Main it = new Main ();
    }
   private static String m (String s){
      System.out.println (s);  return s;
    }
}

Select 1 option

  • A. The program will fail to compile.
  • B. The program will compile without error and will print a, c and b in that order when run.
  • C. The program will compile without error and will print a, b and c in that order when run.
  • D. The program will compile without error and will print c, a and b in that order when run.
  • E. The program will compile without error and will print b, c and a in that order when run.


Correct Option is  : B

Note

First, static statements/blocks are called in the order they are defined.

Hence, a and c will be printed.

Next, instance initializer statements/blocks are called in the order they are defined.

Finally, the constructor is called. So, then it prints b.




PreviousNext

Related