OCA Java SE 8 Method - OCA Mock Question Method 5








Question

What is the output of the following code?

     import com.java2s.*; 
     import static com.java2s.Line.*; 
     public class Main { 
       private static Line l1 = new Line(); 
       private static Line l2 = new Line(); 
       { 
         System.out.println(l1.length); 
       } 
       public static void main(String[] args) { 
         l1.length = 2; 
         l2.length = 8; 
         System.out.println(l1.length); 
       } 
     } 

     package com.java2s; 
     public class Line { 
       public static int length = 0; 
     } 
  1. 02
  2. 08
  3. 2
  4. 8
  5. The code does not compile.
  6. An exception is thrown.




Answer



D.

Note

Main has an instance initializer and not a static initializer.

Since Main is never constructed, the instance initializer does not run.

The other detail is that length is static.

Changes from one object update this common static variable.