2
class A
{
static final int i=10;
static 
{
    System.out.println("Static A");
}

}
public class B {
    public static void main(String[] args)
    {
     System.out.println(A.i);
     }  
  }

In the above code snippet,wheather class A is loading into the memory or not? If class A is loading into the memory why SIB is not executing?If class A is not loading into memory how we able to access its member in class B.

Ravi Godara
  • 497
  • 6
  • 20

2 Answers2

5

A static final int field is a compile-time constant and its value is hard coded into the destination class without a reference to its origin.

Therefore your main class does not trigger the loading of the class containing the field.

Therefore the static initializer in that class is not executed.

Thanks to OP's answer

Community
  • 1
  • 1
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
2

To the Java Language Specification we go

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.

  • T is a class and a static method declared by T is invoked.

  • A static field declared by T is assigned.

  • A static field declared by T is used and the field is not a constant variable (§4.12.4).

  • T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

You've done none of these things from your main(), so the static block is not executed, ie. the class is not initialized.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724