Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This Java Program is always printing only 10 but not printing SB.Why?

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?

like image 225
chandankumar patra Avatar asked Jul 10 '15 07:07

chandankumar patra


1 Answers

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.

like image 69
mziccard Avatar answered Oct 31 '22 09:10

mziccard