OCA Java SE 8 Method - OCA Mock Question Method 9








Question

What is the output of the following code?

     1: package com.java2s; 
     2: public class Line { 
     3:   public static int LENGTH = 5; 
     4:   static {  
     5:     LENGTH = 10; 
     6:   } 
     7:   public static void swing() { 
     8:      System.out.print("swing "); 
     9:   } 
     10: } 

     1: import com.java2s.*; 
     2: import static com.java2s.Line.*; 
     3: public class Main { 
     4:  public static void main(String[] args) { 
     5:    Line.swing(); 
     6:    new Line().swing(); 
     7:    System.out.println(LENGTH); 
     8:  }  
     9: } 
  1. swing swing 5
  2. swing swing 10
  3. Compiler error on line 2 of Main.
  4. Compiler error on line 5 of Main.
  5. Compiler error on line 6 of Main.
  6. Compiler error on line 7 of Main.




Answer



B.

Note

Line runs line 3, setting LENGTH to 5, after runs the static initializer, which sets it to 10.

Line 5 calls the static method and prints swing.

Line 6 calls the static method. Java allows calling a static method through an instance variable.

Line 7 uses the static import on line 2 to reference LENGTH.