3
class Test4 {
     public static void main(String as[]) {
         System.out.println(Hello.x); 
     }

}

class Hello {
    final static int x=10;
    static {
        System.out.println("Hello");                
    }
}

Output: 10

Why it is not printing Hello as per my knowledge if we call static variable then first class is loaded and when class will be loaded then first it should execute static block then static variable will be sent.

Gab
  • 7,869
  • 4
  • 37
  • 68

1 Answers1

11

A static initializer block is executed when the class that contains it is initialized - which is normally when the class is loaded.

You would say that the JVM should load and initialize class Hello when you access Hello.x in class Test4. However, that doesn't happen here, because this is a special case.

static final constants are inlined by the compiler - which means that when this code is compiled, the Hello.x in the main method is replaced at compilation time by the value of the constant, which is 10. Essentially, your code compiles to the same byte code as when you would compile this:

class Test4 {
    public static void main(String[] args) {
        System.out.println(10); // Inlined constant value here!
    }
}

class Hello {
    final static int x = 10;
    static {
        System.out.println("Hello");                
    }
}

Note that class Test4 doesn't really access class Hello in this case - so class Hello is not loaded and the static initializer is not executed when you run Test4.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • class Test4 { public static void main(String[] args) { System.out.println(10); // Inlined constant value here! } } class Hello { final static int x; static { x=10; System.out.println("Hello"); } } – DEEPAK KUMAR Aug 22 '18 at 19:55
  • a/c to your concept, in this case also compiler will replace Hello.x with 10 and result will be 10. But actual result is Hello 10 – DEEPAK KUMAR Aug 22 '18 at 19:57
  • 1
    @DEEPAKKUMAR You slightly modified my code and therefore what I described above doesn't hold anymore. – Jesper Aug 23 '18 at 13:16