Serialization in Java is the process of converting the state of an object into a byte stream, which can be used to recreate the actual Java object in memory. This mechanism is used to persist the object and is mainly used in Hibernate, JMS, JPA, and EJB technologies. The byte stream created is platform-independent, so the object serialized on one platform can be deserialized on a different platform. To make a Java object serializable, we implement the java.io.Serializable interface. The ObjectOutputStream class contains writeObject() method for serializing an Object, and the ObjectInputStream class contains readObject() method for deserializing an object. Only the objects of those classes can be serialized which are implementing java.io.Serializable interface. Serializable is a marker interface that has no data member and method. It is used to "mark" Java classes so that objects of these classes may get certain capability. Some key points to remember while using serialization in Java are:
- Serialization is a marker interface with no method or data member.
- You can serialize an object only by implementing the Serializable interface.
- All the fields of a class must be serializable; otherwise, use the transient keyword.
- The child class doesn’t have to implement the Serializable interface if the parent class does.
- The serialization process only saves non-static data members, but not static or transient data members.
- By default, the String and all wrapper classes implement the Serializable interface.
In summary, serialization in Java is a mechanism that allows the state of an object to be converted into a byte stream, which can be used to recreate the object in memory. It is mainly used to persist the object and transport the code from one JVM to another. To make a Java object serializable, we implement the java.io.Serializable interface, and the ObjectOutputStream class contains writeObject() method for serializing an Object, and the ObjectInputStream class contains readObject() method for deserializing an object.