Skip to content
Advertisement

What happens if import statements can not be resolved?

I am not clear on the following:
A class is loaded by JVM when needed, like lazy initialization, right?
Now if class A does an import of class B which class B actually is not in the file system (e.g. B.class was deleted or not delivered or any reason)
then does class A get loaded and runs if no method of class B is called?
Or class A is not able to run at all since the imports can not be resolved?
Or class A is loaded and run up to a certain point?

Advertisement

Answer

import statement is only important for the compiler. In bytecode all references to other classes are fully qualified. That’s why superflous imports don’t matter at runtime.

In your case JVM will try to load all classes that are required to load and verify A, so it will try to load B immediately, but dependant classes are loaded lazily only when they are needed. Check out the following example:

public class A {

    public static void bar() {
        new B().foo();
    }

    public static void main(String[] args) {
        //bar();
    }

}

Compile A.java and delete B.class. Without calling bar() method your program will run just fine. But once you uncomment piece of code actually using B class you’ll get nasty:

Exception in thread "main" java.lang.NoClassDefFoundError: B
    at A.bar(A.java:4)
    at A.main(A.java:8)
Caused by: java.lang.ClassNotFoundException: B
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 2 more

If B is not available, you’ll get NoClassDefFound or similar.

Advertisement