Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my class is not getting loaded

I am confused with the output of the below code. I know first static block gets executed after class loading but why is my class Test6 not getting loaded. Can someone please clarify.

package com.vikash.General;

public class Test5 {

    public static void main(String[] args) {
        System.out.println(Test6.FOO);
    }
    static {
        System.out.println("Initializing B");
    }
}
class Test6{

    public static final String FOO = "foo";
    static {
        System.out.println("Initializing A");
    }
}
like image 542
Vikash Mishra Avatar asked May 19 '16 09:05

Vikash Mishra


People also ask

Why could not find or load main class?

Reasons to Occur Error The error generates because the JVM fails to load the main class or package name. There are some other reasons that generate the same error, as follows: The class has been declared in the wrong package. Dependencies missing from the CLASSPATH.

How are classes loaded?

Classloading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need for class initialization occurs. If Class is loaded before it's actually being used it can sit inside before being initialized.

How a class is loaded into memory?

The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren't loaded into memory all at once, but when required by an application. At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes into memory dynamically.


2 Answers

Test6.FOO refers to Test6, but the field is a public static final String initialized from a compile-time constant, so it will be inlined by the compiler, and Test6 does not need to be loaded at all.

like image 200
Thilo Avatar answered Nov 04 '22 08:11

Thilo


It seems to be because the compiler is inlining the reference to the string literal "foo", so the JRE doesn't actually bother loading Test6 to get it.

If you make a change such as:

public static final String FOO = new String("foo");

then the class Test6 does get loaded (and its static block gets executed).

like image 26
khelwood Avatar answered Nov 04 '22 10:11

khelwood