notes
  • computer-networking
    • extend-wifi-with-router
    • how-the-internet-works
    • idk
    • networking-devices
    • osi-model
    • tcp-ip
    • Types of VPN
  • databases
    • Foreign Keys
    • Redis
    • simple-queries
  • devops
    • ansible
    • Manual deployment
    • docker
    • Workflow file
    • nginx
    • promethues-grafana
    • terraform
  • hardware
    • Power
  • home-server
    • proxmox-basics
    • proxmox-setup
    • storage
  • languages-frameworks
    • programming-paradigms
    • programming-languages
      • Regex Notes
      • c
        • basics
        • pointers-memory
      • cpp
        • basics
        • running-cpp
      • php
        • basics
        • choizez
        • frameworks
          • laravel
      • python
        • venv
        • concepts
          • Using lambda
        • frameworks
          • django
            • django
            • start
      • java
        • advanced
          • functional-programming
          • reactive-programming
        • concepts
          • how-java-works
          • serialization
          • sockets
          • threads
        • extra
          • collection-framework
          • generics-and-wildcards
          • Regular Expressions (Regex)
          • streams
        • frameworks
          • orm
        • fundamentals
          • OOP
          • conditionals
          • data-structures
          • data-types
          • exceptions
          • files
          • Functions (aka method)
          • Loops
          • packages
          • type-casting
      • javascript
        • frameworks
          • morgan
          • Using Sequelize with PostgreSQL in JavaScript
  • operating-system
    • basics
    • linux-directories
    • Basic Unix Terminal Commands
  • others
    • dark-web
    • piracy
  • system-design
    • system-design
  • web-dev
    • full-stack
  • books
    • sicp
      • Recursion thought process
      • 1
        • 1.1
        • 1.2
        • 1.3
      • 2
        • 2.1
  • certifications
    • aws-certified-cloud-practitioner
      • core-services
      • other-services
    • comptia-a+
      • Cloud
      • hardware
      • Important terms
      • Important terms
      • Troubleshooting
  • cloud
    • aws
      • aws-cli
      • aws-ec2-deployment
  • dsa
    • algorithms
      • back-tracking
      • bfs
      • Binary Search
      • bit-manipulation
      • Bubble sort
      • bucket-sort
      • counting-sort
      • dfs
      • Divide & Conquer
      • djikstras-algorithm
      • dynamic-programming
      • external-sorting
      • greedy-algorithm
      • Heap sort
      • Insertion sort
      • kadanes-algorithm
      • Merge sort
      • Permutation
      • quick-sort
      • Radix Sort
      • recurrence-relation
      • recursion
      • Selection sort
      • sliding-window
      • subset
      • time-space-complexity
      • topological-sort
      • tree-traversals
      • Two Pointers Technique
    • data-structures
      • data-structures
  • security
    • authentication
      • What is JWT (JSON Web Token)?
    • software-architecture-design
      • design-patterns
Powered by GitBook
On this page
  • Serialization
  • How to serialize an object?
  • Deserialize
  • Serial Version UID
  1. languages-frameworks
  2. programming-languages
  3. java
  4. concepts

serialization

Serialization

Serialization is the process of converting objects into a byte stream ...to enable data storage, sharing, and retrieval in a compact, standardized format..

How to serialize an object?

// Class you want to serialize should `implements Serializable`
public class User implements Serializable {
    private String name;
    private String password;

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
public class Main {
    public static void main(String[] args) throws IOException {

        User user = new User("aloy","aaaaa");

        // Create file to serialize to
        FileOutputStream fileOutputStream = new FileOutputStream("UserInformation.ser");

        // Create output stream to serialize to file
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

        // Serialize object to a byte stream
        objectOutputStream.writeObject(user);

        // Close streams
        objectOutputStream.close();
        fileOutputStream.close();
    }
}

Result :

Object serialized into byte code to file UserInformation.ser

Deserialize

Deserialize is the process of converting a byte stream into objects (essentially reverse of serialize)

Since we stored a User object with name 'aloy' and password 'aaaaa' and serialized it into UserInformation.ser , now we want to deserialize it .

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        // Create file to serialize from
        FileInputStream fileInputStream = new FileInputStream("UserInformation.ser");

        // Create output stream to serialize the file input stream
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        // Create User object to store deserialized object
        User user = (User) objectInputStream.readObject();

        // Close streams
        fileInputStream.close();
        objectInputStream.close();

        // View deserialized object
        System.out.println(user.toString());

    }
}

Result :

Take Note: Can used transient to mark variables in object to be not serialized

Serial Version UID

When deserializing an object, the JVM compares the serialVersionUID of the class being loaded with the serialVersionUID that was stored with the object.

If they match, deserialization proceeds; if they don't match, a InvalidClassException is thrown, indicating a class version mismatch.

To avoid this...

Make sure that both class structure of the serialized objects should be the same on both sides

or

Set a unique serial version UID for both object classes for serialization and deserialization

public class User implements Serializable {
    // A unique serial version UID for object class used in both serialization and deserialization , if match = deserialization proceeds
    private static final long serialVersionUID = 123454321;

    // Other class members and methods
}
Previoushow-java-worksNextsockets

Last updated 1 month ago

Alt text
Deserialize