Vikash Mishra
Vikash Mishra

Reputation: 97

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");
    }
}

Upvotes: 5

Views: 599

Answers (4)

Thilo
Thilo

Reputation: 262504

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.

Upvotes: 9

sotondolphin
sotondolphin

Reputation: 223

Test6 is not initialized at all.

the foo is static, which means it can be used before class is intitialized and after a class is load.

Upvotes: -3

khelwood
khelwood

Reputation: 59112

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).

Upvotes: 2

Helios
Helios

Reputation: 851

Use a class loader you will get the desired output

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

Upvotes: 0

Related Questions