Java OCA OCP Practice Question 2966

Question

Given:

public class Main {
   static int x;
   {//from w ww.  j a v a  2s  .co  m
      int[] ia2 = { 4, 5, 6 };
   }
   static {
      int[] ia = { 1, 2, 3 };
      for (int i = 0; i < 3; i++)
         System.out.print(ia[i] + " ");
      x = 7;
      System.out.print(x + " ");
   }
}

And, if the code compiles, the invocation:

java Main 

What is the result?

  • A. Compilation fails.
  • B. "1 2 3 7", with no exception thrown.
  • C. "1 2 3 7", followed by an exception.
  • D. "1 2 3", followed by an ExceptionInInitializerError
  • E. ExceptionInInitializerError is thrown before any output.
  • F. Some other exception is thrown before any other output.


C is correct.

Note

If you invoke a.class file with no main(), the static init blocks will execute before throwing a NoSuchMethodError exception.

(Note that you don't need to know the name of the NoSuchMethodError exception to get this question correct!).




PreviousNext

Related