Is it possible to unload a class in Java?

Class unloading in Java is possible, but it cannot be triggered directly by application code. A class becomes eligible for unloading only when the ClassLoader that loaded it is no longer reachable and can be garbage collected. The JVM then removes the class metadata from memory during the garbage collection process.

Key Points: • Java does not provide an API to explicitly unload a class. • A class can be unloaded only when its associated ClassLoader becomes unreachable and all instances of the class are no longer referenced. • Class unloading helps free Metaspace memory and is commonly used in application servers, plugin systems, and hot-deployment environments.

Example: In a web application server, each deployed application is often loaded by a separate ClassLoader. When the application is undeployed, the ClassLoader and its loaded classes can be garbage collected, allowing the JVM to unload those classes and reclaim memory.

Interview Tip: A concise interview answer is: Yes, class unloading is possible in Java, but it happens indirectly. A class is unloaded only when its ClassLoader becomes eligible for garbage collection and there are no active references to the class or its instances. Java does not provide a direct mechanism to unload classes manually.