Wednesday, March 25, 2015

JAVA Class Loader

Applications written programming languages, such as C and C++, are compiled into native, machine-specific instructions and saved as an executable file. But in case of java specific application this is different. JAVA is dynamically compiled programming languages. In Java, compiler generate the .class files and it remain as-is until loaded into the Java Virtual Machine (JVM) . Classes are loaded into the JVM on an 'as needed' basis. And when a loaded class depends on another class, then that class is loaded as well.

Lets try to understand using our famous HelloWorld

public class HelloWorld {
   public static void main(String argv[]) {
      System.out.println("Hello World");
   }
}
If you run this class specifying the -verbose:class command-line option, so that it prints what classes are being loaded

java -verbose:class HelloWorld



[Opened C:\Program Files\Java\jre1.5.0\lib\rt.jar]
[Opened C:\Program Files\Java\jre1.5.0\lib\jsse.jar]
[Opened C:\Program Files\Java\jre1.5.0\lib\jce.jar]
[Opened C:\Program Files\Java\jre1.5.0\lib\charsets.jar]
[Loaded java.lang.Object from shared objects file]
[Loaded java.io.Serializable from shared objects file]
[Loaded java.lang.Comparable from shared objects file]
[Loaded java.lang.CharSequence from shared objects file]
[Loaded java.lang.String from shared objects file]
[Loaded java.lang.reflect.GenericDeclaration from shared objects file]
[Loaded java.lang.reflect.Type from shared objects file]
[Loaded java.lang.reflect.AnnotatedElement from shared objects file]
[Loaded java.lang.Class from shared objects file]
[Loaded java.lang.Cloneable from shared objects file]
[Loaded java.lang.ClassLoader from shared objects file]
[Loaded java.lang.System from shared objects file]
[Loaded java.lang.Throwable from shared objects file]
---
---
[Loaded java.security.BasicPermissionCollection from shared objects file]
[Loaded java.security.Principal from shared objects file]
[Loaded java.security.cert.Certificate from shared objects file]
[Loaded HelloWorld from
Hello World
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file]
As you can see, the Java runtime classes required by the application class (HelloWorld) are loaded first.

No comments: