Why is my class not loading

I am confused with the output of the code below. I know that the first static block starts after the class loads, but why my Test6 class does not load. Can someone 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"); } } 
+5
source share
4 answers

Test6.FOO refers to Test6 , but the field is public static final String initialized from compilation time constant, therefore it will be embeddable by the compiler , and Test6 does not need to be loaded at all.

+9
source

It seems that the compiler is inserting a reference to the string literal "foo" , so the JRE does not actually load Test6 to get it.

If you make changes, for example:

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

then the Test6 class Test6 loaded (and its static block is executed).

+2
source

Using the class loader you will get the desired result

 Class.forName("<package>.Test6"); 
0
source

Test6 is not initialized at all.

foo is static, which means that it can be used before the class is interintegrated and after the class is loaded.

-3
source

All Articles