What is default Serialization in Java? Serializable and Externalizable Interface

What is Serialization in Java
Serialization in Java is a process to persist any Java Object's state into File System or convert them into byte stream to transfer over the network to other JVM or program. Serialization in Java is done by JVM by employing default Serialization process which persists all of Object's state except transient variable and a static variable. How Serialization works in Java  is another popular Java Serialization interview question, well It's easy to make any Java class Serializable, the class needs to implements java.io.Serializable interface and JVM will automatically serialize its instance when passed over to java.io.ObjectOutputStream using writeObject(). Serializable interface is also called marker interface or tag interface because it does not contain any method or behavior and just used to tag a class, by seeing a class implementing Serializable JVM knows that it needs to serialize an instance of this class.

Default Serialization in Java

We can customize default Serialization process by using java.io.Externalizable interface. The difference between Serializable and Externalizable in Java is another important question related to Java Serialization process. In fact, it's advised that not to use default serialization process as its very fragile and use the custom binary form for your objects and implement Serialization using java.io.Externalizable interface.

One example of how fragile default Serialization process is SerialVersionUID. SerialVersionUID is a unique id associated with serialized form of class and its depends on upon class's structure. If you implement an interface, SerialVersionUID generated by Default Serialization process would be different, which means you can not deserialize class with the new code. This can be avoided by declaring a long constant called serialversionUID in the class itself.

Another intrinsic cost of Serialization is maintenance. Serialized form of a class is part of its public API and once you commit that you need to support it a life long otherwise you won't be able to load serialized instances by old code. This can be minimized by using custom Serialize form.

What is Serialization in Java - default Serialization processThat's all on What is Serialization in Java. Serialization is the core of Java RMI protocol and one of the popular technique of storing Object's state in Java.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Other Java tutorials from Java67 blog:
Top 10 Java Concurrency Questions answers
Top Java questions for beginners in Java
Difference between HashSet and HashMap in Java
What is Class file in Java

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.