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: }
B.
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.