Home Java javaTutorial Serialization and Deserialization In Java

Serialization and Deserialization In Java

Oct 31, 2024 am 06:12 AM

Serialization and Deserialization In Java

In advanced Java, serialization and deserialization are processes to save and restore the state of an object, making it possible to store objects in files or databases, or transfer them over a network. Here’s a breakdown of these concepts and their application

1️⃣ Serialization

Serialization is the process of converting an object into a stream of bytes. This byte stream can be saved to a file, sent over a network, or stored in a database. In Java, the Serializable interface is used to indicate that a class can be serialized.

✍ Steps to serialize an object:

▶️ Implement the Serializable interface.

▶️ Use ObjectOutputStream and FileOutputStream to write the object to a file or output stream.

▶️ Call the writeObject() method on ObjectOutputStream.

?Code Example:

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }
}

public class SerializeDemo {
    public static void main(String[] args) {
        Employee emp = new Employee("John Doe", 101);

        try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(emp);
            System.out.println("Serialized data is saved in employee.ser");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Copy after login

Here, employee.ser is a serialized file that stores the object’s byte stream.

2️⃣ Deserialization
Deserialization is the reverse process, where the byte stream is converted back into a copy of the original object. This enables you to recreate the object’s state after it’s been stored or transferred.

✍ Steps to deserialize an object:

▶️ Use ObjectInputStream and FileInputStream to read the object from the file or input stream.

▶️ Call the readObject() method on ObjectInputStrea

?Code Example:

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializeDemo {
    public static void main(String[] args) {
        Employee emp = null;

        try (FileInputStream fileIn = new FileInputStream("employee.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            emp = (Employee) in.readObject();
            System.out.println("Deserialized Employee...");
            System.out.println("Name: " + emp.name);
            System.out.println("ID: " + emp.id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Copy after login

This will retrieve the object’s original state, allowing access to its fields as they were before serialization.

3️⃣ Advanced Serialization Topics

▶️ Custom Serialization: Override writeObject() and readObject() for customized serialization.

▶️ Externalizable Interface: Provides full control over serialization, requiring the implementation of writeExternal() and readExternal() methods.

▶️ Transient Fields: Use the transient keyword to avoid serializing specific fields (e.g., sensitive data like passwords).

✍ Advantages of Serialization:

▶️ Allows saving the state of an object for future use.

▶️ Facilitates the transfer of complex data objects over networks.

? Briefly Explain Code Example

import java.io.*;

class Student implements Serializable {
    private  static   final long serialVersionUId = 1l;
    private String name ;
    private int  age;
    private String Address;

    public Student(String name,int age,String Address){
        this.name = name;
        this.age = age;
        this.Address = Address;
    }
    public void setName(String name){
        this.name = name;
    }
    public void setAge(int age){
        this.age = age;
    }
    public void setAddress(String Address){
        this.Address = Address;
    }

    public String getName(){
        return name;
    }
    public String getAddress(){
        return Address;
    }
    public int getAge(){
        return age;
    }


    public String toString(){
        return ("Student name is "+this.getName()+", age is "+this.getAge()+", and address is "+this.getAddress());
    }
}

public class  JAVA3_Serialization {
    // when you implement Serializable then you must be write a serialVersionUId because when it serialise and deserialize it uniquely identify in the network
    // when u update ur object or anything then you have to update the serialVersionUId increment .
    // private  static   final long serialVersionUId = 1l;

    // transient  int x ;
    // If you do not want a particular value to serialise and Deserialize.
    // the value x, when you don't serialise and Deserialize Then transient you used.

    public static void main(String[] args) {

        Student student = new Student("kanha",21,"angul odisha");

        String filename = "D:\Advance JAVA\CLS3 JAVA\Test.txt"; // store the data in this location
        FileOutputStream fileOut = null; // write file
        ObjectOutputStream objOut = null; // create object
        //Serialization
        try {
            fileOut = new FileOutputStream(filename);
            objOut = new ObjectOutputStream(fileOut);
            objOut.writeObject(student);

            objOut.close();
            fileOut.close();

            System.out.println("Object has been serialise =\n"+student);
        } catch (IOException ex){
            System.out.println("error will occure");
        }

        //Deserialization
        FileInputStream fileIn = null;
        ObjectInputStream objIn = null;
        try {
            fileIn = new FileInputStream(filename);
            objIn = new ObjectInputStream(fileIn);
            Student object =(Student) objIn.readObject();
            System.out.println("object has been Deserialization =\n"+object);

            objIn.close();
            fileIn.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

Copy after login

✍ Key Notes:

▶️ Only non-static and non-transient data members are serialized by default.

▶️ Serializable objects must ensure compatibility between versions if the class is modified after serialization.

For more insights, feel free to mention your GitHub for in-depth examples and code samples! Let me know if you'd like any specific adjustments.

GitHub - https://github.com/Prabhanjan-17p

The above is the detailed content of Serialization and Deserialization In Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles