5
public class Test {
    public static void main(String[] args) {
        System.out.println(Hello.a1);
    }
}

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

This code is always printing 10 but not printing SB.Why?

Krzysztof Trzos
  • 6,040
  • 12
  • 51
  • 85

3 Answers3

10

A static final field is implemented as a compile-time constant which is replicated in the accessing method/class without any reference to the context of definition (its class). This is why accessing it does not trigger the static class block.

This is basically due to the final keyword. If you remove final as follows:

public class Test {
  public static void main(String[] args) {
    System.out.println(Hello.a1);
  }
}
class Hello{
  static int a1=10;
  static{
    System.out.println("SB");
  }
}

You will see that SB is printed as expected.

mziccard
  • 1,987
  • 6
  • 17
5

You are using static final constant variable. This variable will be replaced at the compile time by the actual constant value, in-order to increase the performance. If you have a look at the compiled binary code (Yes you cannot ;) but technically speaking with an assumption) it will be something similar to this:

public class Test {
    public static void main(String[] args) {
        System.out.println(10); // Constant
    }
}

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

Based on this code, class Hello will not be loaded into the RAM. So it will not print the SB.

Gobinath
  • 862
  • 1
  • 14
  • 21
-3

Your static code block willbe invoked, when you create an instance of the class. Try this:

public class Test {
    public static void main(String[] args) {
        Hello h = new Hello();
        System.out.println(Hello.a1);
    }
}

class Hello {
    static final int a1 = 10;
    static {
        System.out.println("SB");
    }
}
Marcel Härle
  • 163
  • 2
  • 6
  • 7
  • 1
    static initialization block is invoked when the class is loaded into the memory. Instance initialization block is the one invoked, when you create an instance of the class. – Gobinath Jul 10 '15 at 07:57