Java OCA OCP Practice Question 959

Question

What is the output of the following code?

1: package mypkg; 
2: public class MyClass { 
3:  public static int LENGTH = 5; 
4:  static {  //from www  . j  av  a 2 s  . com
5:    LENGTH = 10; 
6:  } 
7:  public static void swing() { 
8:    System.out.print("swing "); 
9:  } 
10: } 

1: import mypkg.*; 
2: import static mypkg.MyClass.*; 
3: public class Main { 
4:  public static void main(String[] args) { 
5:    MyClass.swing(); 
6:    new MyClass().swing(); 
7:    System.out.println(LENGTH); 
8:  }  
9: } 
  • A. swing swing 5
  • B. swing swing 10
  • C. Compiler error on line 2 of Main.
  • D. Compiler error on line 5 of Main.
  • E. Compiler error on line 6 of Main.
  • F. Compiler error on line 7 of Main.


B.

Note

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

Line 5 calls the static method normally and prints swing.

Line 6 also 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.




PreviousNext

Related