Serialization in Java is a mechanism that converts an object’s state into a byte stream. Deserialization is its reverse process. Through deserialization, an actual Java object is created in memory from a byte stream. Such a mechanism persists in the object. The byte stream so created from serialization does not depend on any platform. Any other platform can deserialize the object serialized on one platform without issue.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Thus, the entire process of serialization and deserialization is JVM-independent. To serialize a class object, you must implement the java.io.Serializable interface. Serializable in Java is a marker interface. It has no fields or methods to implement. This process makes a class serializable, resembling an Opt-In process.
Serialization in Java is implemented by the two classes ObjectInputStream and ObjectOutputStream. All that is required is to have a wrapper over them so they can be saved to a file or sent over a network.
Concept of Serialization in Java
The class ObjectOutputStream, a serialization class mentioned in the above section, contains several writing methods for writing various data types, but one method is the most popular.
public final void writeObject( Object x ) throws IOException
You can use the above method to serialize an object. This method also sends it to the output stream. In the same way, ObjectInputStream class contains the method for object deserializing.
public final Object readObject() throws IOException, ClassNotFoundException
The deserialization method retrieves the object from a stream and deserializes the same. The return value is again an object, so all needed is to cast it to a relevant data type.
Two conditions must be met for a successful serialization of a class.
- io. The class must implement a serializable interface.
- All fields of the class must be serializable. If even one field is not serializable, it should be marked transient.
If someone needs to check if a class is serializable, the simple solution is to check if the class implements the java.io.Serializable method; if it does, then it is serializable. If it’s not, then it’s not. One should notice that when serializing an object to a file, the standard practice is to give the file a .ser extension.
Methods
If the class contains these methods, they are used for serialization in Java.
1. Method of Serialization in Java
Method | Description |
public final void writeObject (Object obj) throws IOException {} | This will write the specified object to the ObjectOutputStream. |
public void flush() throws IOException {} | This will flush the current output stream. |
public void close() throws IOException {} | This will close the current output stream. |
2. Method of Deserialization in Java
Method | Description |
public final Object readObject() throws IOException, ClassNotFoundException{} | This will read an object from the input stream. |
public void close() throws IOException {} | This will close ObjectInputStream. |
Example of Serialization in Java
An example in Java is provided here to demonstrate how serialization works in Java. We created an Employee class to study some features, and the code is provided below. This employee class implements the Serializable interface.
public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a letter to " + name + " " + address); } }
When this program finishes executing, it will create a file named employee.ser. This program does not provide a guaranteed output, rather it is for explanatory purposes only, and the objective is to understand its use and to work.
import java.io.*; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Rahul Jain"; e.address = "epip, Bangalore"; e.SSN = 114433; e.number = 131; try { FileOutputStream fileOut = new FileOutputStream("https://cdn.educba.com/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data saved in /tmp/employee.ser"); } catch (IOException i) { i.printStackTrace(); } } }
The below-described DeserializeDemo program deserializes the above Employee object created in the Serialize Demo program.
import java.io.*; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("https://cdn.educba.com/tmp/employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Employee class is not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); } }
Output:
Deserialized Employee…
Name: Rahul Jain
Address: epip, Bangalore
SSN: 0
Number:131
Some important points related to the program above are provided below:
- The try/catch block above tries to catch a ClassNotFoundException. This is declared by the readObject() method.
- A JVM can deserialize an object only if it finds the bytecode for the class.
- If the JVM does not find a class during the deserialization, it will throw ClassNotFoundException.
- The readObject () return value is always cast to an Employee reference.
- When the object was serialized, the SSN field had an initial value of 114433, which was not sent to the output stream. Because of the same, the deserialized Employee SSN field object is 0.
Conclusion
Above, we introduced serialization concepts and provided examples. Let’s understand the need for serialization in our concluding remarks.
- Communication: If two machines that are running the same code need to communicate, the easy way out is that one machine should build an object containing information that it would transmit and then serialize that object before sending it to the other machine. The method may not be perfect, but it accomplishes the task.
- Persistence: If you want to store the state of an operation in a database, you first serialize it to a byte array and then store the byte array in the database for retrieval later.
- Deep Copy: If creating a replica of an object is challenging and writing a specialized clone class is difficult, then the goal can be achieved by serializing the object and then de-serializing it into another object.
- Cross JVM Synchronization: JVMs running on different machines and architectures can be synchronized.
The above is the detailed content of Serialization in Java. For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
