Wednesday, 22 August 2012

When a class is loaded and initialized in JVM - Java


Classloading and initialization in Java
Understanding of when a class is loaded and initialized in JVM is one of the fundamental concept of Java programming language. Thanks to Java language specification we have everything clearly documented and explained, but many Java programmer still doesn't know when a class is loaded or when a class is initialized in Java. Class loading and initialization seems confusing and complex to many beginners and its true until having some experience in belt its not always easy to get into subtle details of How JVM works in Java. In this Java tutorial we will see when class loading occurs in Java and when and how class and interface are initialized in Java. I will not go into detail of ClasLoader or How ClassLoader works in  Java, that is subject of another post I am planning just to keep this article focused and concise. There are several articles on Java fundamentals in Javarevisited like How HashMap works in Java and How Garbage collection works in Java. If you are interested you can also check those.

When Class is loaded in Java
Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.

When a Class is initialized in Java
After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.

2) an static method of Class is invoked.
3) an static field of Class is assigned.
4) an static field of class is used which is not a constant variable.
5) if Class is a top level class and an assert statement lexically nested within class is executed.

Reflection can also cause initialization of class. Some methods of java.lang.reflect package may cause class to be initialized. JLS Strictly says that a class should not be initialized by any reason other than above.

How Class is initialized in Java

class loading and initialization in Java - When exampleNow we know what triggers initialization of a class in Java, which is precisely documented in Java language specification. Its also important to know in which order various fields (static and non static), block (static an non static), various classes (sub class and super class) and various interfaces (sub interface, implementation class and super interface) is initialized in Java. Infact many Core Java interview question and SCJP question based on this concept because it affect final value of any variable if its initialized on multiple places. Here are some of the rules of class initialization in Java:

1) Classes are initialized from top to bottom so field declared on top initialized before field declared in bottom
2) Super Class is initialized before Sub Class or derived class in Java
3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type  of Sub Class, Sub Interface or by implementation class of interface.

4) interface initialization in Java doesn't cause super interfaces to be initialized.
5) static fields are initialized during static initialization of class while non static fields are initialized when instance of class is created. It means static fields are initialized before non static fields in Java.

6)non static fields are initialized by constructors in Java. sub class constructor implicitly call super class constructor before doing any initialization, which guarantees that non static or instance variables of super class is initialized before sub class.

Examples of  class initialization in Java:
Here is an example of when class is initialized in Java. In this example we will see which classes are initialized in Java.

/**
 * Java program to demonstrate class loading and initialization in Java.
 */

public
 class ClassInitializationTest {

    public static void main(String args[]) throws InterruptedException {
 
        NotUsed o = null; //this class is not used, should not be initialized
        Child t = new Child(); //initializing sub class, should trigger super class initialization
        System.out.println((Object)o == (Object)t);
    }
}

/**
 * Super class to demonstrate that Super class is loaded and initialized before Subclass.
 */

class Parent {
    static { System.out.println("static block of Super class is initialized"); }
    {System.out.println("non static blocks in super class is initialized");}
}

/**
 * Java class which is not used in this program, consequently not loaded by JVM
 */

class NotUsed {
    static { System.out.println("NotUsed Class is initialized "); }
}

/**
 * Sub class of Parent, demonstrate when exactly sub class loading and initialization occurs.
 */

class Child extends Parent {
    static { System.out.println("static block of Sub class is initialized in Java "); }
    {System.out.println("non static blocks in sub class is initialized");}
}

Output:
static block of Super class is initialized
static block of Sub class is initialized in Java
non static blocks in super class is initialized
non static blocks in sub class is initialized
false


Observation:
1) Super class is initialized before sub class in Java.
2) Static variables or blocks are initialized before non static blocks or fields.
3) Not used class is not initialized at all because its not been used, none of the cases mentioned on JLS or above which triggers initialization of class is not happened here.

Let's have a look on another example of class initialization in Java:

/**
 * Another Java program example to demonstrate class initialization and loading in Java.
 */


public class ClassInitializationTest {

    public static void main(String args[]) throws InterruptedException {
 
       //accessing static field of Parent through child, should only initialize Parent
       System.out.println(Child.familyName);
    }
}

class Parent {
    //compile time constant, accessing this will not trigger class initialization
    //protected static final String familyName = "Lawson";
 
    protected static String familyName = "Lawson";
 
    static { System.out.println("static block of Super class is initialized"); }
    {System.out.println("non static blocks in super class is initialized");}
}

Output:
static block of Super class is initialized
Lawson


Observation
1. Here class initialization occurs because static field is accessed which is not a compile time constant. had you declare "familyName" compile time constant using final keyword in Java (as shown in commented section) class initialization of super class would not have occurred.

2) Only super class is initialized even though static field is referenced using sub type.

There is another example of class initialization related to interface on JLS which explains clearly that initialization of sub interfaces does not trigger initialization of super interface. I highly recommend reading JLS 14.4 for understating  class loading and initialization in more detail.

That's all on When a class is initialized and loaded in Java. We have seen clear guidelines form JLS regarding class initialization. We have also seen the order on which super type and sub type are initialized and order of initialization for both static and non static fields and blocks in Java.

Standard Edition of Java Platform




Packages
java.appletProvides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context.
java.awtContains all of the classes for creating user interfaces and for painting graphics and images.
java.awt.colorProvides classes for color spaces.
java.awt.datatransferProvides interfaces and classes for transferring data between and within applications.
java.awt.dndDrag and Drop is a direct manipulation gesture found in many Graphical User Interface systems that provides a mechanism to transfer information between two entities logically associated with presentation elements in the GUI.
java.awt.eventProvides interfaces and classes for dealing with different types of events fired by AWT components.
java.awt.fontProvides classes and interface relating to fonts.
java.awt.geomProvides the Java 2D classes for defining and performing operations on objects related to two-dimensional geometry.
java.awt.imProvides classes and interfaces for the input method framework.
java.awt.im.spiProvides interfaces that enable the development of input methods that can be used with any Java runtime environment.
java.awt.imageProvides classes for creating and modifying images.
java.awt.image.renderableProvides classes and interfaces for producing rendering-independent images.
java.awt.printProvides classes and interfaces for a general printing API.
java.beansContains classes related to developing beans -- components based on the JavaBeansTM architecture.
java.beans.beancontextProvides classes and interfaces relating to bean context.
java.ioProvides for system input and output through data streams, serialization and the file system.
java.langProvides classes that are fundamental to the design of the Java programming language.
java.lang.annotationProvides library support for the Java programming language annotation facility.
java.lang.instrumentProvides services that allow Java programming language agents to instrument programs running on the JVM.
java.lang.managementProvides the management interface for monitoring and management of the Java virtual machine as well as the operating system on which the Java virtual machine is running.
java.lang.refProvides reference-object classes, which support a limited degree of interaction with the garbage collector.
java.lang.reflectProvides classes and interfaces for obtaining reflective information about classes and objects.
java.mathProvides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal).
java.netProvides the classes for implementing networking applications.
java.nioDefines buffers, which are containers for data, and provides an overview of the other NIO packages.
java.nio.channelsDefines channels, which represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations.
java.nio.channels.spiService-provider classes for the java.nio.channels package.
java.nio.charsetDefines charsets, decoders, and encoders, for translating between bytes and Unicode characters.
java.nio.charset.spiService-provider classes for the java.nio.charset package.
java.rmiProvides the RMI package.
java.rmi.activationProvides support for RMI Object Activation.
java.rmi.dgcProvides classes and interface for RMI distributed garbage-collection (DGC).
java.rmi.registryProvides a class and two interfaces for the RMI registry.
java.rmi.serverProvides classes and interfaces for supporting the server side of RMI.
java.securityProvides the classes and interfaces for the security framework.
java.security.aclThe classes and interfaces in this package have been superseded by classes in the java.security package.
java.security.certProvides classes and interfaces for parsing and managing certificates, certificate revocation lists (CRLs), and certification paths.
java.security.interfacesProvides interfaces for generating RSA (Rivest, Shamir and Adleman AsymmetricCipher algorithm) keys as defined in the RSA Laboratory Technical Note PKCS#1, and DSA (Digital Signature Algorithm) keys as defined in NIST's FIPS-186.
java.security.specProvides classes and interfaces for key specifications and algorithm parameter specifications.
java.sqlProvides the API for accessing and processing data stored in a data source (usually a relational database) using the JavaTM programming language.
java.textProvides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages.
java.text.spiService provider classes for the classes in the java.text package.
java.utilContains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).
java.util.concurrentUtility classes commonly useful in concurrent programming.
java.util.concurrent.atomicA small toolkit of classes that support lock-free thread-safe programming on single variables.
java.util.concurrent.locksInterfaces and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.
java.util.jarProvides classes for reading and writing the JAR (Java ARchive) file format, which is based on the standard ZIP file format with an optional manifest file.
java.util.loggingProvides the classes and interfaces of the JavaTM 2 platform's core logging facilities.
java.util.prefsThis package allows applications to store and retrieve user and system preference and configuration data.
java.util.regexClasses for matching character sequences against patterns specified by regular expressions.
java.util.spiService provider classes for the classes in the java.util package.
java.util.zipProvides classes for reading and writing the standard ZIP and GZIP file formats.
javax.accessibilityDefines a contract between user-interface components and an assistive technology that provides access to those components.
javax.activation 
javax.activityContains Activity service related exceptions thrown by the ORB machinery during unmarshalling.
javax.annotation 
javax.annotation.processingFacilities for declaring annotation processors and for allowing annotation processors to communicate with an annotation processing tool environment.
javax.cryptoProvides the classes and interfaces for cryptographic operations.
javax.crypto.interfacesProvides interfaces for Diffie-Hellman keys as defined in RSA Laboratories' PKCS #3.
javax.crypto.specProvides classes and interfaces for key specifications and algorithm parameter specifications.
javax.imageioThe main package of the Java Image I/O API.
javax.imageio.eventA package of the Java Image I/O API dealing with synchronous notification of events during the reading and writing of images.
javax.imageio.metadataA package of the Java Image I/O API dealing with reading and writing metadata.
javax.imageio.plugins.bmpPackage containing the public classes used by the built-in BMP plug-in.
javax.imageio.plugins.jpegClasses supporting the built-in JPEG plug-in.
javax.imageio.spiA package of the Java Image I/O API containing the plug-in interfaces for readers, writers, transcoders, and streams, and a runtime registry.
javax.imageio.streamA package of the Java Image I/O API dealing with low-level I/O from files and streams.
javax.jws 
javax.jws.soap 
javax.lang.modelClasses and hierarchies of packages used to model the Java programming language.
javax.lang.model.elementInterfaces used to model elements of the Java programming language.
javax.lang.model.typeInterfaces used to model Java programming language types.
javax.lang.model.utilUtilities to assist in the processing of program elements and types.
javax.managementProvides the core classes for the Java Management Extensions.
javax.management.loadingProvides the classes which implement advanced dynamic loading.
javax.management.modelmbeanProvides the definition of the ModelMBean classes.
javax.management.monitorProvides the definition of the monitor classes.
javax.management.openmbeanProvides the open data types and Open MBean descriptor classes.
javax.management.relationProvides the definition of the Relation Service.
javax.management.remoteInterfaces for remote access to JMX MBean servers.
javax.management.remote.rmiThe RMI connector is a connector for the JMX Remote API that uses RMI to transmit client requests to a remote MBean server.
javax.management.timerProvides the definition of the Timer MBean.
javax.namingProvides the classes and interfaces for accessing naming services.
javax.naming.directoryExtends the javax.naming package to provide functionality for accessing directory services.
javax.naming.eventProvides support for event notification when accessing naming and directory services.
javax.naming.ldapProvides support for LDAPv3 extended operations and controls.
javax.naming.spiProvides the means for dynamically plugging in support for accessing naming and directory services through thejavax.naming and related packages.
javax.netProvides classes for networking applications.
javax.net.sslProvides classes for the secure socket package.
javax.printProvides the principal classes and interfaces for the JavaTM Print Service API.
javax.print.attributeProvides classes and interfaces that describe the types of JavaTM Print Service attributes and how they can be collected into attribute sets.
javax.print.attribute.standardPackage javax.print.attribute.standard contains classes for specific printing attributes.
javax.print.eventPackage javax.print.event contains event classes and listener interfaces.
javax.rmiContains user APIs for RMI-IIOP.
javax.rmi.CORBAContains portability APIs for RMI-IIOP.
javax.rmi.sslProvides implementations of RMIClientSocketFactory and RMIServerSocketFactory over the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocols.
javax.scriptThe scripting API consists of interfaces and classes that define Java TM Scripting Engines and provides a framework for their use in Java applications.
javax.security.authThis package provides a framework for authentication and authorization.
javax.security.auth.callbackThis package provides the classes necessary for services to interact with applications in order to retrieve information (authentication data including usernames or passwords, for example) or to display information (error and warning messages, for example).
javax.security.auth.kerberosThis package contains utility classes related to the Kerberos network authentication protocol.
javax.security.auth.loginThis package provides a pluggable authentication framework.
javax.security.auth.spiThis package provides the interface to be used for implementing pluggable authentication modules.
javax.security.auth.x500This package contains the classes that should be used to store X500 Principal and X500 Private Crendentials in aSubject.
javax.security.certProvides classes for public key certificates.
javax.security.saslContains class and interfaces for supporting SASL.
javax.sound.midiProvides interfaces and classes for I/O, sequencing, and synthesis of MIDI (Musical Instrument Digital Interface) data.
javax.sound.midi.spiSupplies interfaces for service providers to implement when offering new MIDI devices, MIDI file readers and writers, or sound bank readers.
javax.sound.sampledProvides interfaces and classes for capture, processing, and playback of sampled audio data.
javax.sound.sampled.spiSupplies abstract classes for service providers to subclass when offering new audio devices, sound file readers and writers, or audio format converters.
javax.sqlProvides the API for server side data source access and processing from the JavaTM programming language.
javax.sql.rowsetStandard interfaces and base classes for JDBC RowSet implementations.
javax.sql.rowset.serialProvides utility classes to allow serializable mappings between SQL types and data types in the Java programming language.
javax.sql.rowset.spiThe standard classes and interfaces that a third party vendor has to use in its implementation of a synchronization provider.
javax.swingProvides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
javax.swing.borderProvides classes and interface for drawing specialized borders around a Swing component.
javax.swing.colorchooserContains classes and interfaces used by the JColorChooser component.
javax.swing.eventProvides for events fired by Swing components.
javax.swing.filechooserContains classes and interfaces used by the JFileChooser component.
javax.swing.plafProvides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.
javax.swing.plaf.basicProvides user interface objects built according to the Basic look and feel.
javax.swing.plaf.metalProvides user interface objects built according to the Java look and feel (once codenamed Metal), which is the default look and feel.
javax.swing.plaf.multiProvides user interface objects that combine two or more look and feels.
javax.swing.plaf.synthSynth is a skinnable look and feel in which all painting is delegated.
javax.swing.tableProvides classes and interfaces for dealing with javax.swing.JTable.
javax.swing.textProvides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.htmlProvides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parserProvides the default HTML parser, along with support classes.
javax.swing.text.rtfProvides a class (RTFEditorKit) for creating Rich-Text-Format text editors.
javax.swing.treeProvides classes and interfaces for dealing with javax.swing.JTree.
javax.swing.undoAllows developers to provide support for undo/redo in applications such as text editors.
javax.toolsProvides interfaces for tools which can be invoked from a program, for example, compilers.
javax.transactionContains three exceptions thrown by the ORB machinery during unmarshalling.
javax.transaction.xaProvides the API that defines the contract between the transaction manager and the resource manager, which allows the transaction manager to enlist and delist resource objects (supplied by the resource manager driver) in JTA transactions.
javax.xmlDefines core XML constants and functionality from the XML specifications.
javax.xml.bindProvides a runtime binding framework for client applications including unmarshalling, marshalling, and validation capabilities.
javax.xml.bind.annotationDefines annotations for customizing Java program elements to XML Schema mapping.
javax.xml.bind.annotation.adaptersXmlAdapter and its spec-defined sub-classes to allow arbitrary Java classes to be used with JAXB.
javax.xml.bind.attachmentThis package is implemented by a MIME-based package processor that enables the interpretation and creation of optimized binary data within an MIME-based package format.
javax.xml.bind.helpersJAXB Provider Use Only: Provides partial default implementations for some of the javax.xml.bind interfaces.
javax.xml.bind.utilUseful client utility classes.
javax.xml.cryptoCommon classes for XML cryptography.
javax.xml.crypto.domDOM-specific classes for the javax.xml.crypto package.
javax.xml.crypto.dsigClasses for generating and validating XML digital signatures.
javax.xml.crypto.dsig.domDOM-specific classes for the javax.xml.crypto.dsig package.
javax.xml.crypto.dsig.keyinfoClasses for parsing and processing KeyInfo elements and structures.
javax.xml.crypto.dsig.specParameter classes for XML digital signatures.
javax.xml.datatypeXML/Java Type Mappings.
javax.xml.namespaceXML Namespace processing.
javax.xml.parsersProvides classes allowing the processing of XML documents.
javax.xml.soapProvides the API for creating and building SOAP messages.
javax.xml.stream 
javax.xml.stream.events 
javax.xml.stream.util 
javax.xml.transformThis package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.
javax.xml.transform.domThis package implements DOM-specific transformation APIs.
javax.xml.transform.saxThis package implements SAX2-specific transformation APIs.
javax.xml.transform.staxProvides for StAX-specific transformation APIs.
javax.xml.transform.streamThis package implements stream- and URI- specific transformation APIs.
javax.xml.validationThis package provides an API for validation of XML documents.
javax.xml.wsThis package contains the core JAX-WS APIs.
javax.xml.ws.handlerThis package defines APIs for message handlers.
javax.xml.ws.handler.soapThis package defines APIs for SOAP message handlers.
javax.xml.ws.httpThis package defines APIs specific to the HTTP binding.
javax.xml.ws.soapThis package defines APIs specific to the SOAP binding.
javax.xml.ws.spiThis package defines SPIs for JAX-WS.
javax.xml.ws.wsaddressingThis package defines APIs related to WS-Addressing.
javax.xml.xpathThis package provides an object-model neutral API for the evaluation of XPath expressions and access to the evaluation environment.
org.ietf.jgssThis package presents a framework that allows application developers to make use of security services like authentication, data integrity and data confidentiality from a variety of underlying security mechanisms like Kerberos, using a unified API.
org.omg.CORBAProvides the mapping of the OMG CORBA APIs to the JavaTM programming language, including the class ORB, which is implemented so that a programmer can use it as a fully-functional Object Request Broker (ORB).
org.omg.CORBA_2_3The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java[tm] Standard Edition 6.   These changes occurred in recent revisions to the CORBA API defined by the OMG.  The new methods were added to  interfaces derived from the corresponding interfaces in the CORBA package.  This provides backward compatibility and avoids breaking the JCK tests.
org.omg.CORBA_2_3.portableProvides methods for the input and output of value types, and contains other updates to theorg/omg/CORBA/portable package.
org.omg.CORBA.DynAnyPackageProvides the exceptions used with the DynAny interface (InvalidValueInvalidInvalidSeq, andTypeMismatch).
org.omg.CORBA.ORBPackageProvides the exception InvalidName, which is thrown by the method ORB.resolve_initial_references and the exception InconsistentTypeCode, which is thrown by the Dynamic Any creation methods in the ORB class.
org.omg.CORBA.portableProvides a portability layer, that is, a set of ORB APIs that makes it possible for code generated by one vendor to run on another vendor's ORB.
org.omg.CORBA.TypeCodePackageProvides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.
org.omg.CosNamingProvides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackageThis package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackageThis package contains Exception classes for the org.omg.CosNaming package.
org.omg.DynamicThis package contains the Dynamic module specified in the OMG Portable Interceptor specification,http://cgi.omg.org/cgi-bin/doc?ptc/2000-08-06, section 21.9.
org.omg.DynamicAnyProvides classes and interfaces that enable traversal of the data value associated with an any at runtime, and extraction of the primitive constituents of the data value.
org.omg.DynamicAny.DynAnyFactoryPackageThis package contains classes and exceptions from the DynAnyFactory interface of the DynamicAny module specified in the OMG The Common Object Request Broker: Architecture and Specification,http://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 9.2.2.
org.omg.DynamicAny.DynAnyPackageThis package contains classes and exceptions from the DynAny interface of the DynamicAny module specified in the OMG The Common Object Request Broker: Architecture and Specificationhttp://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 9.2.
org.omg.IOPThis package contains the IOP module specified in the OMG document The Common Object Request Broker: Architecture and Specificationhttp://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 13.6.
org.omg.IOP.CodecFactoryPackageThis package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackageThis package is generated from the IOP::Codec IDL interface definition.
org.omg.MessagingThis package contains the Messaging module specified in the OMG CORBA Messaging specification,http://cgi.omg.org/cgi-bin/doc?formal/99-10-07.
org.omg.PortableInterceptorProvides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.
org.omg.PortableInterceptor.ORBInitInfoPackageThis package contains the exceptions and typedefs from the ORBInitInfo local interface of thePortableInterceptor module specified in the OMG Portable Interceptor specification, http://cgi.omg.org/cgi-bin/doc?ptc/2000-08-06, section 21.7.2.
org.omg.PortableServerProvides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.CurrentPackageProvides method implementations with access to the identity of the object on which the method was invoked.
org.omg.PortableServer.POAManagerPackageEncapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackageAllows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.portableProvides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.ServantLocatorPackageProvides classes and interfaces for locating the servant.
org.omg.SendingContextProvides support for the marshalling of value types.
org.omg.stub.java.rmiContains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.
org.w3c.domProvides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
org.w3c.dom.bootstrap 
org.w3c.dom.events 
org.w3c.dom.ls 
org.xml.saxThis package provides the core SAX APIs.
org.xml.sax.extThis package contains interfaces to SAX2 facilities that conformant SAX drivers won't necessarily support.
org.xml.sax.helpersThis package contains "helper" classes, including support for bootstrapping SAX-based applications.

How to create read only List, Map and Set in Java – unmodifiable example


Read only List, Map and Set in Java
Read only List means a List where you can not perform modification operations like addremove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java, as shown in below example. Any modification in read only List will result in java.lang.UnSupportedOperationException in Java.  This read-only List example is based on Java 5 generics but also applicable  to other Java version like JDK 1.4 or JDK 1.3, just remove Generics code i.e. angle bracket which is not supported prior to Java 5. One common mistake programmer makes is that assuming fixed size List and read only List as same. As shown in our 3 example of converting Array to Array List , we can use Arrays.asList() method to create and initialized List at same line. List implementation returned by this method is fixed size and it doesn’t allow adding or removal of element but it is not read only because you can update objects by callingset(index) method. How to make a collection read only is also a popular Java collection interview question, which makes this Java collection tutorial even more important.

Read only List, Set and Map Example - Java

Example to create read only List Set and Map in JavaHere is sample Java program which demonstrate method of creating read only ListSet and Map in Java. You can make any ListSet or Map implementation as read only by following code example. Just remember that Collections.unModifiableList() , Collections.unModifiableSet() and Collections.unModifiableMap() method in Java. On read only List add, remove and set operation is not permitted, on read only Set you can not add or remove elements and in read only Map you can not put new entries or update existing entries. You can use same methods to convert any List implementation like ArrayListLinkedList or Vector to read only ArrayList , LinkedList and Vector in Java.

package example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Java program to create read only List, Set and Map in Java. You can first create
 * a List or Set and than make it unmodifiable or read-only by
 * using  Collections.unmodifiableList() or Collections.unmodifiableSet() method.
 *
 * @author Javin Paul
 */

public class ReadOnlyListSetMap {
 
    public static void main(String args[]) {            
       
        // creating List in Java
        List<String> contents = new ArrayList<String>();
     
        // initializing List in Java
        contents.add("Example");
        contents.add("Tutorial");
        contents.add("Program");
     
     
        // Currently This List is not read only, you can add or remove elements from List
        contents.add("Tips"); //should not be allowed if List is read only.
     
        System.err.println("normal List in Java : " + contents);
     
        //creating readonly List from contents
        contents = Collections.unmodifiableList(contents);
     
        //java.lang.UnsupportedOperationException -- no modification in read only list
     
       //not allowed as it is read-only List in Java 
       contents.add("Can I add object into read only List - No");

       
        contents.remove("Example"); //remove not allowed in read only list
     
        //java.lang.UnSupportedOperation - List update not allowed
        contents.set(0"Can I override or set object in read-only Set - No");

     
        //Creating read only Set in Java
        //similar to read-only List you can also create a Set which is read only 
        //i.e. addition , removal and modification operation is not permitted on list
     
     
        //Creating a Set based on contents of List       
        Set<String> readOnlySet = new HashSet<String>(contents);
     
        System.out.println("original Set in Java : " + readOnlySet);

        //Set is not yet read-only you can still add elements into Set
        readOnlySet.add("Override");

        System.out.println("Set before making read only : " + readOnlySet);
     
        //making Set readonly in Java - no add remove or set operation permitted
        readOnlySet = Collections.unmodifiableSet(readOnlySet);
     
        //trying to add element in read only Set - java.lang.UnSupportedOperationException
        readOnlySet.add("You can not add element in read Only Set");
     
        //trying to remove element from read only set
        readOnlySet.remove("Example"); //you can not remove elements from read only Set
     
     
     
        // Creating read only Map in Java
        // Similar to List and Set you can also create read only or unmodifiable Map in Java
        // add , remove and override is not allowed on read only Map in Java
     
        Map<StringString> contries = new HashMap<StringString>();      
        contries.put("India""New Delhi");
     
        //Map is not read only yet, you can still add entries into
        contries.put("UK""London");
     
        System.out.println("Map in Java before making read only: " + contries);
     
        //Making Map read only in Java
        Map readOnlyMap = Collections.unmodifiableMap(contries);
       
        //you can not put a new entry in read only Map in Java
        readOnlyMap.put("USA""Washington"); //java.lang.UnSupportedOperation 
       
        //you can not remove keys from read only Map in Java
        readOnlyMap.remove("UK"); //java.lang.UnSupportedOperation
     
    }
 
}


That’s all on how to create read only ListSet and Map in Java. Its very easy to make any List implementation read only by wrapping it with Collections.unModifiableList(). Use same technique to convert any other Collection into read only in Java.