What class loading means
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A Java program is not copied into memory all at once. The JVM brings in each class only when the running code first needs it, and this work is called class loading.
Class loading: bringing a class into the JVM
Class loading is how the JVM finds a class's .class file, reads it into memory and prepares it the first time the class is needed.
Class loading is the JVM's work of finding a class's bytecode, reading it into memory and getting the class ready to use. The bytecode usually comes from a .class file that javac wrote.
Example 1 · A class that is never used is never loaded
class Student { static { System.out.println("Student class is ready"); }}
class Topper { static { System.out.println("Topper class is ready"); }}
public class LazyLoadingDemo { static { System.out.println("LazyLoadingDemo class is ready"); }
public static void main(String[] args) { System.out.println("main started"); new Student(); System.out.println("Student object created"); if (args.length > 0) { new Topper(); System.out.println("Topper object created"); } System.out.println("main finished"); }}LazyLoadingDemo class is ready main started Student class is ready Student object created main finished
What this code does
javacmakes three files:LazyLoadingDemo.class,Student.classandTopper.class. The main class is ready beforemain started, because the JVM must load it to runmain.Studentis set up only whennew Student()runs, not at start-up. With no command-line arguments,new Topper()is never reached, soTopper class is readynever prints.
When you compile a file with three classes, you get three .class files: one per class. Each one is loaded on its own, at its own time. Until a class is loaded, your program cannot create its objects or call its static methods. In the program below, a static block prints a line when its class is set up. Here that line serves as a simple signal that the class has been loaded. The Loading, Linking and Initialization lesson shows that loading and setting up are really separate steps.
.class file. The JVM reads bytecode, not your .java source.Lazy loading: a class is loaded the first time it is needed
Lazy loading means the JVM loads a class only when the running code first uses it, for example to create an object or call a static method. A class that the code never reaches is never loaded.
Example 2 · Run it again with an argument
javac LazyLoadingDemo.javajava LazyLoadingDemo topperLazyLoadingDemo class is ready main started Student class is ready Student object created Topper class is ready Topper object created main finished
What this code does
- The word
toppermakesargs.lengthequal 1, so theifblock runs andTopperis needed for the first time. - Same class files, different run, different classes loaded: loading follows what the code actually does, not what is written in the source.
Example 3 · Exam portal: each service is loaded once, on first use
class ResultService { static { System.out.println(" [ResultService loaded]"); }
static String result(String roll) { return roll + ": result sent"; }}
class RevaluationService { static { System.out.println(" [RevaluationService loaded]"); }
static String apply(String roll) { return roll + ": revaluation request saved"; }}
class PdfExporter { static { System.out.println(" [PdfExporter loaded]"); }
static String export(String roll) { return roll + ": marksheet.pdf ready"; }}
public class ExamPortalDemo { public static void main(String[] args) { String[][] requests = { {"result", "21CS041"}, {"result", "21CS042"}, {"revaluation", "21CS041"}, {"result", "21CS043"} }; for (String[] r : requests) { System.out.println("Request: " + r[0] + " " + r[1]); String reply = switch (r[0]) { case "result" -> ResultService.result(r[1]); case "revaluation" -> RevaluationService.apply(r[1]); default -> PdfExporter.export(r[1]); }; System.out.println(" " + reply); } }}Request: result 21CS041 [ResultService loaded] 21CS041: result sent Request: result 21CS042 21CS042: result sent Request: revaluation 21CS041 [RevaluationService loaded] 21CS041: revaluation request saved Request: result 21CS043 21CS043: result sent
What this code does
ResultServiceis loaded at the first result request and then reused: the second and third result requests do not print the loaded line again.RevaluationServicearrives only when the first revaluation request comes. Nobody asked for a PDF, soPdfExporteris never loaded, even though its code is in the program.
The main class is always first, because the JVM must load it to find main. After that, classes come in one by one as the code reaches them. A class is loaded once and then reused. The second new Student() or the hundredth call to a static method does not load the class again. Lazy loading keeps start-up fast and saves memory: a big app does not pay for features the user never opens.
Watching loads with -verbose:class and -Xlog:class+load
-verbose:class is a JVM option that prints one line for every class the JVM loads, at the moment it loads it. On Java 9 and later, -Xlog:class+load prints the same lines through the JVM's unified logging system.
# print every class as it is loaded (Java 9+ style)java -Xlog:class+load LazyLoadingDemo# older option, same lines on Java 9+java -verbose:class LazyLoadingDemo# show only the lines you care about (Windows)java -Xlog:class+load LazyLoadingDemo | findstr Student# the same on macOSjava -Xlog:class+load LazyLoadingDemo | grep StudentExample 4 · Watching the loads with -verbose:class
java -verbose:class LazyLoadingDemo[0.034s][info][class,load] java.lang.Object source: shared objects file [0.034s][info][class,load] java.io.Serializable source: shared objects file ... [0.111s][info][class,load] LazyLoadingDemo source: file:/C:/.../lazy/ ... LazyLoadingDemo class is ready main started [0.114s][info][class,load] Student source: file:/C:/.../lazy/ Student class is ready Student object created main finished [0.115s][info][class,load] java.lang.Shutdown source: shared objects file ...
What this code does
- A real run on JDK 21 (HotSpot), trimmed with
...and with the folder path shortened. That run printed about 500 load lines; around 490 JDK classes were loaded beforemaineven started. Times and counts differ on every machine and JDK version. Studentappears in the log right aftermain started, at the momentnew Student()runs.Toppernever appears, which proves it was never loaded.
source: shared objects filemeans the class came from the CDS archive (Class Data Sharing): a file of ready-made JDK classes that ships with the JDK so start-up is faster.source: jrt:/java.basemeans the class was read from the JDK's own module image.source: file:/...means the class came from your class path, here the current folder.- Your program's own output appears between the log lines, so you can see exactly when each class arrives.
The Class object that represents a loaded class
When the JVM loads a class, it creates one Class object for it: an object of type java.lang.Class that describes the class, its name, its superclass and its methods. Every object of that class points to this same Class object.
Example 5 · One Class object per class
import java.util.ArrayList;
class Student { String name;
Student(String name) { this.name = name; }}
public class ClassObjectDemo { public static void main(String[] args) throws ClassNotFoundException { Student riya = new Student("Riya"); Student arjun = new Student("Arjun");
Class<?> a = Student.class; // class literal Class<?> b = riya.getClass(); // from an object Class<?> c = Class.forName("Student"); // from a name, at run time
System.out.println("Same object? " + (a == b && b == c)); System.out.println("Shared by every Student? " + (riya.getClass() == arjun.getClass())); System.out.println("Name: " + a.getName()); System.out.println("Superclass: " + a.getSuperclass().getName());
Class<?> list = new ArrayList<String>().getClass(); System.out.println("Full name: " + list.getName()); System.out.println("Simple name: " + list.getSimpleName()); System.out.println("Is interface? " + list.isInterface()); }}Same object? true Shared by every Student? true Name: Student Superclass: java.lang.Object Full name: java.util.ArrayList Simple name: ArrayList Is interface? false
What this code does
Student.class,riya.getClass()andClass.forName("Student")all return the sameClassobject, because the class was loaded once.getName()gives the full name with the package (java.util.ArrayList);getSimpleName()gives the short name.Class.forNamecan throwClassNotFoundException, a checked exception, somaindeclares it.
You can get it in three ways: the class literal Student.class, obj.getClass() on any object, or Class.forName("Student") with the name as a string. All three give the very same object, so == between them is true.
A class is identified by its name and its class loader
A class loader is the part of the JVM (or a Java object) that finds and loads classes. Inside a running JVM, a class is identified by two things together: its full name, such as java.lang.String, and the class loader that loaded it.
class Student {}
public class WhoLoadedDemo { public static void main(String[] args) { System.out.println(Student.class.getClassLoader().getName()); System.out.println(String.class.getClassLoader()); }}app null
- Your own classes are loaded by the application class loader, whose name is
app(Java 9 and later). - Core classes such as
Stringare loaded by the JVM's built-in bootstrap loader, which Java shows asnull. - Two different loaders can each load a class named
Student. The JVM then has two different classes with the same name. The Custom Class Loaders lesson shows this in action.
Next step
Check your understanding
12 quick questions