Tuesday, 17 January 2012

How does Java find and load classes ?

Classes are loaded in java using the order defined below :-

1.Bootstrap class loader - Java platform specific classes like Object,System,String etc which are defined in rt.jar(inside jre/lib folder) are loaded first.
Bootstrap classes are found using the value of the bootstrap class path which is stored in the sun.boot.class.path system property.

2.Extension class loader - BootStrap class loader uses delegation model to load Extension Classes that use the Java Extension mechanism.
These are bundled as .jar files located in the extensions directory (jre/lib/ext).Extension class loader makes custom APIs available to all applications running on the Java platform.

3.Application class loader - application specfic classes developed by programmers and which do not take advantage of extension class loader are defined in Classpath.
Java Run time environment looks into classpath and loads the classes defined in it.

In order to find out how java finds classes and how does class loader work , lets look into the below cases :-

1. rt.jar is removed from jre/lib directory

Result :
Compile,but error at run time.
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

public class TestClassLoading
{
    public static void main(String[] args)
    {
        String str="Hello";
        System.out.println(str);
       
    }
}

Observation : Java Run time environment tried to load the Object class first as it is a Top class of all classes , and since rt.jar is not present
in bootstrap path , we get the error in run time.



2. String Class is removed from jre/lib/rt.jar java.lang package
Result :
Compile,but error at run time.
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/String

public class TestClassLoading
{
    public static void main(String[] args)
    {
        String str="Hello";
        System.out.println(str);
       
    }
}
Observation : Java Run time environment has loaded the Object class and then tried to load the classes present in the Program , String class is referneced in main method
so though rt.jar is present in bootstrap path , it does not have String class, so we get the error at run time.


3.
A.ext folder is removed from jre/lib directory

Result :
Compiletime error.
sun.text.resources.FormatData_ar_AE can not be resolved.

B.ext folder is placed in jre/lib directory
Result :
Compiled ,and executed successfully

import sun.text.resources.FormatData_ar_AE;
public class TestClassLoading
{
    public static void main(String[] args)
    {
        String str="Hello";
        System.out.println(str);
       
    }
}
Observation : javac and java both follow the same path in order to find the class.

2 comments: