How classes are loaded when we have 2 classes (1 public and other default) in a java file?

Viewed 47

Here I have a java file where I have 2 classes in the same file.

class loadingClass1{
    int a;
    int b;
}

public class classLoading{
    public static void main(String[] args) {
        
    }
}

Since I have not created any instance of loadingClass1 in main method, will jvm still load the class or leave it?

class loadingClass1{
    int a;
    int b;
}

public class classLoading{
    public static void main(String[] args) {
        loadingClass1 c = new loadingClass1();
    }
}

In this case how jvm will act? (as per my understanding, the jvm will first load classLoading class and when it invokes the main method, to create the instance of the loadingClass1 it will load that class into classLoader. Is it correct?)

Thank you

1 Answers

Your understanding is right. The compiler will generate two separate files for your two classes. You can investigate this behavior if you log the static initalizer of the class or use the -verbose:class flag.

Related