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");
}
}
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With