RSS Feed for This PostCurrent Article

Java: Static Initializer Problem

Have a look at the following code

   1: public class StaticTest {
   2:     
   3:     static {
   4:         name = "my name";
   5:     }
   6:  
   7:     public static String name = null;
   8:  
   9:  
  10:     public static void main(String[] args) {
  11:         System.out.println(StaticTest.name);
  12:  
  13:     }
  14: }

The output is “null”, which may surprise some of you.

Look at the code generated by the compiler, as shown below, you can see that the code logic is different from what you expected.

   1: import java.io.PrintStream;
   2:  
   3: public class StaticTest
   4: {
   5:  
   6:     public static String name = "my name";
   7:  
   8:     public StaticTest()
   9:     {
  10:     }
  11:  
  12:     public static void main(String args[])
  13:     {
  14:         System.out.println(name);
  15:     }
  16:  
  17:     static 
  18:     {
  19:         name = null;
  20:     }
  21: }

Now we reverse the order by putting the variable declaration before the static initializer code block

   1:  
   2: public class StaticTest {
   3:     
   4:     public static String name = null;
   5:  
   6:     static {
   7:         name = "my name";
   8:     }
   9:  
  10:  
  11:     public static void main(String[] args) {
  12:         System.out.println(StaticTest.name);
  13:  
  14:     }
  15: }

The variable now is printed correctly. Looking at the compiler generated code, it is what we have expected.

   1: import java.io.PrintStream;
   2:  
   3: public class StaticTest
   4: {
   5:  
   6:     public static String name = null;
   7:  
   8:     public StaticTest()
   9:     {
  10:     }
  11:  
  12:     public static void main(String args[])
  13:     {
  14:         System.out.println(name);
  15:     }
  16:  
  17:     static 
  18:     {
  19:         name = "my name";
  20:     }
  21: }

Another way to produce the correct result is remove the initialization of the variable during declaration.

   1:  
   2: public class StaticTest {
   3:     static {
   4:         name = "my name";
   5:     }
   6:  
   7:     public static String name ;
   8:  
   9:     public static void main(String[] args) {
  10:         System.out.println(StaticTest.name);
  11:  
  12:     }
  13: }

So the order of your code block and variable declarations does matter.


Trackback URL


Sorry, comments for this entry are closed at this time.