Example.java
public class Example {
static final int i = 10;
static int j = 20;
static {
System.out.println("Example class loaded and initialized");
}
}
Use.java
import java.util.Scanner;
public class Use {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int ch = 1;
while(ch != 0) {
System.out.print("Enter choice: ");
ch = sc.nextInt();
if (ch == 1) {
System.out.println("Example's i = " + Example.i);
} else if(ch == 2){
System.out.println("Example's j = " + Example.j);
}
}
}
}
When I run with java -verbose:class Use
, and give input as 1
then output is 10
i.e the constant i
value. But Example
class is not loaded yet.
However, when I give input as 2
, only then Example
class is loaded into the JVM, as visible by the verbose output, and then static block inside Example is executed and also j
's value initialized and then printed.
My Query is: If for the input 1
i.e when the static final (constant) value of a class Example
is requested in another class Use
, then from where is that constant value fetched if the class Example
was never loaded into the JVM till then?
When and how was the static final i
intialized and store into the JVM memory?