topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Serialization and Deserialization in Java with Example - Scaler Topics description: Learn about Serialization in Java by Scaler Topics. Java serialization is usually used when there is a need to send your data over the network or to store in files. author: Rishabh Mahajan category: Java --- :::section{.main} **Serialization** in java is the process of converting the state of an object into a byte stream. A byte stream is a Java I/O (Input/Output) stream, essentially a flow of data that a programmer can read from or write to. Byte Streams read or write one byte of data at a time. However, we must convert these byte streams back to their respective Objects to use them again. This reverse process of converting an object into byte-stream is called **Deserialization**. ![what is serialization in java](https://scaler.com/topics/images/what-is-serialization-in-java.webp) Serialization in Java can be implemented using the `java.io.Serializable` interface. The `writeObject()` method of the `ObjectOutputStream` class is used for serializing an Object. To make a Java object serializable, we implement the `java.io.Serializable` interface. While **Serialization**, the `writeObject()` method is used. Meanwhile, in **Deserialization**, the `readObject()` method is used. Also, **for an object to be made serializable, it is mandatory for the object’s class to implement the Serializable interface.** The `Serializable` interface tells the JVM (Java Virtual Machine) that the objects of this class are ready for serialization and/or deserialization. The code that we write is called source code. We know that machines do not understand the human language. To bridge the gap, we need to translate the source code. This is where the JVM comes in. It converts source code to something called bytecode, which is then translated to the machine language. ### Advantages of Serialization * Serialization in java enables object state persistence and facilitates object transmission over a network. * Implemented via the java.io.Serializable interface, it marks classes to grant serialization capability. * Alongside saving and transferring object states, serialization supports marker interfaces like Cloneable and Remote, providing essential functionalities without data members or methods. ### Important Points * Any associated objects must also implement the Serializable interface to be serialized properly. * To exclude a non-static data member from serialization, mark it as transient. During deserialization, the object's constructor isn't invoked. * When a parent class implements the Serializable interface, its child class inherits this behaviour. However, if only the child class implements Serializable, it doesn't automatically apply to the parent. * Serialization in java only preserves non-static data members; static and transient data members are excluded from the process. ::: :::section{.main} ## Examples of Serialization and Deserialization in Java Let’s look at one example to show how serialization in Java works programmatically. Here, we are creating a `Student` class and serializing the object of the `Student` class. ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class Student implements java.io.Serializable { public String stu_Name; public String stu_Addr; public int stu_Id; public static void main(String[] args) { Student std = new Student(); std.stu_Name = "George"; std.stu_Addr = "ABC,XYZ"; std.stu_Id = 1; try { FileOutputStream fileOut = new FileOutputStream("storeObject.txt"); //Serializing object ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(std); // Close the output stream. out.close(); // Close the file. fileOut.close(); System.out.printf("Object serialized"); } catch (IOException i) { i.printStackTrace(); } } } ``` **Explanation:** * The code snippet shows serialization of an `Object` of type `Student`. A text file called `storeObject` is created with the help of the `FileOutputStream` class. * `FileOutputStream` is an output stream that is used to write data into a file. Next, the `ObjectOutputStream` class is used to write the object as an `OutputStream`. * `writeObject(Object ob)` is used to serialize objects into byte-streams. * So the object is converted to a byte stream. Hence, serialization is complete. Next, let’s look at the code for deserializing the same object. We will use the `readObject()` method of the `ObjectInputStream` class to deserialise the object. ```java import java.io.*; public class Student implements java.io.Serializable { public String stu_Name; public String stu_Addr; public int stu_Id; public static void main(String[] args) { // Create a Student object. Student std = new Student(); std.stu_Name = "George"; std.stu_Addr = "ABC,XYZ"; std.stu_Id = 1; // To hold the deserialized byte-stream Student deserializedStudent; try { // Serializing the student object - std FileOutputStream fileOut = new FileOutputStream("storeObject.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(std); out.close(); fileOut.close(); // Serialization complete System.out.printf("Object serialized"); // Deserialization process FileInputStream fileIn = new FileInputStream("storeObject.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); //Deserialization deserializedStudent = (Student) in.readObject(); in.close(); fileIn.close(); // Printing the deserialized object. System.out.println("Deserialized Student..."); System.out.println("Name: " + deserializedStudent.stu_Name); System.out.println("Address: " + deserializedStudent.stu_Addr); } catch (IOException i) { i.printStackTrace(); } catch (Exception e) { System.out.println("Class not found"); e.printStackTrace(); return; } } } ``` Output: ```plaintext Deserialized Student... Name: George Address: ABC,XYZ ``` **Explanation:** * Just like the previous code snippet, the object is first serialized. * Here, the `storeObject.txt` file is accessed with the help of the `FileInputStream`, which is used to read data from a file. * Next, the object is retrieved with the help of the `ObjectInputStream`, which converts the objects from the byte stream that was written using `ObjectOutputStream`. * `readObject()` method is used to deserialize objects. Hence, the process from object to byte stream is complete. ![how do we serialize an object in java](https://scaler.com/topics/images/how-do-we-serialize-an-object-in-java.webp) ::: :::section{.main} ## Java Serialization with Inheritance (IS-A Relationship) When a parent class implements the Serializable interface, the child classes do not have to do so. This is a case of Serialization with Inheritance. Inheritance is when a child class extends a parent class and inherits its properties. Hence, the names - parent and child. **Example:** ```java import java.io.*; class Child implements java.io.Serializable { public String stu_Name; Child(String stu_Name) { this.stu_Name = stu_Name; } } public class Student extends Child { public String stu_Addr; public int stu_Id; public Student(String stu_Name, String stu_Addr, int stu_Id) { super(stu_Name); this.stu_Addr = stu_Addr; this.stu_Id = stu_Id; } public static void main(String[] args) { Student s = new Student("George", "ABC, XYZ", 1); try { FileOutputStream fileOut = new FileOutputStream("storeObject.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(s); out.close(); fileOut.close(); System.out.printf("Object serialized"); } catch (IOException i) { i.printStackTrace(); } } } ``` Since `Student` extends `Child`, which extends the Serializable interface, there is no need for the `Student` class itself to extend this interface. ::: :::section{.main} ## Java Serialization with Aggregation (HAS-A Relationship) If a class Student has an object of type Child and if class Student were to implement the Serializable interface and not B, Java would throw a `NotSerializableException`. Let’s see in the code: **Example:** ```java import java.io.*; class Child { public String stu_Name; Child(String stu_Name) { this.stu_Name = stu_Name; } } // Non-serializable class public class Student implements java.io.Serializable { String stu_Addr; int stu_Id; Child child; public Student(String stu_Addr, int stu_Id) { this.stu_Addr = stu_Addr; this.stu_Id = stu_Id; } } ``` The above code snippet would throw a `NotSerializableException` when a class `Student` object is serialized. Class `Student` is said to have a relationship with class Child. This is called Aggregation (**HAS-A Relationship**). ::: :::section{.main} ## Java Serialization with the Static Data Member Static data members are volatile and can change during the serialization to deserialization process. Static means the data member is the only copy of the class, and any change made to it will be felt throughout the program. In other words, it belongs to the whole class. Consider the below code where x is a static variable: **Example:** ```java import java.io.*; public class Main implements java.io.Serializable { static int x = 50; public static void main(String[] args) { Main s = new Main(); System.out.println("Value before serialization: " + x); try { // Serialization FileOutputStream fileOut = new FileOutputStream("storeObject.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(s); out.close(); // Serialization complete // Static member value changed x = 48; fileOut.close(); System.out.println("Object serialized"); // Deserialization FileInputStream fileIn = new FileInputStream("storeObject.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); s = (Main) in.readObject(); in.close(); fileIn.close(); // Value of static member not revived System.out.println("Value after serialization: " + x); } catch (IOException i) { i.printStackTrace(); } catch (Exception e) { System.out.println("Class not found"); e.printStackTrace(); return; } } } ``` **Output:** ```plaintext Value before serialization: 50 Object serialized Value after serialization: 48 ``` **Explanation:** * In the above code, the class has a static member of type int, with the value 50, when an object of this class was serialized. After this object was serialized, the program changed the value of the static member to 48. * When this object is deserialized, the value of the static member is not restored to its original value of 50, which was the value when the object was serialized, because the static member belongs to its class and not the object. * Hence, the process of [serialization and deserialization](https://www.scaler.com/topics/java/serialization-and-deserialization/ ) only works on the object of a class. It doesn't affect a static member of a class, and therefore, when the object was deserialized, the value of a static member is found to be 48 and not 50. ::: :::section{.main} ## Java Serialization with Array or Collection When dealing with arrays or collections, all contained objects must be serializable. If any object within them lacks serializability, the serialization process will encounter failure. ::: :::section{.main} ## SerialVersionUID The `serialVersionUID` is a constant. So, while the whole object to byte-stream to object takes place, we need to be sure that the conversion from byte-stream to object is correct. * We use the `serialVersionUID` attribute to remember versions of a `Serializable` class and verify that a class and the serialized object are compatible. * Please note that this `serialVersionUID` is optional. If the programmer does not define this constant, Java does it for us. ```java private static final long serialVersionUID = 1234567L; ``` The serialization at runtime associates with each serializable class a `serialVersionUID`, which is used during deserialization to verify that the object that was converted to byte-stream is the one that is being retrieved. What if we do not want to save, i.e. serialize, the state of some data member of the class that gets serialized? In that case, we use a reserved keyword with the data member(s) that we do not want to serialize, like below: ```java transient String stu_Addr; ``` Take a look at the example below: ```java import java.io.*; public class Student implements java.io.Serializable { public String stu_Name; transient String stu_Addr; public int stu_Id; public static void main(String[] args) { Student s = new Student(); s.stu_Name = "George"; s.stu_Addr = "ABC,XYZ"; s.stu_Id = 1; try { FileOutputStream fileOut = new FileOutputStream("storeObject.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(s); out.close(); fileOut.close(); // Serialization complete System.out.println("Object serialized"); FileInputStream fileIn = new FileInputStream("storeObject.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); // Deserialization in process. s = (Student) in.readObject(); // Close input stream and the file. in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (Exception e) { System.out.println("Class not found"); e.printStackTrace(); return; } // Print the values of the deserialized object. System.out.println("Deserialized Student..."); System.out.println("Name: " + s.stu_Name); System.out.println("Address: " + s.stu_Addr); } } ``` **Output:** ```plaintext Object serialized Deserialized Student... Name: George Address: null ``` **Explanation:** The last print statement will return null as `stu_Addr` is a transient variable, and as such, it will not get serialized and will lose its value. ::: :::section{.main} ## Java Transient vs Final Regarding serialization, final variables are serialized directly by their values. Therefore, marking a final variable as transient serves no purpose, as the compiler assigns the value to the final variable. In Java, marking a data member as transient means it won't be serialized when the object is written to a file or transferred over a network. ```java class Student implements Serializable{ transient int id; public Student(int id) { this.id = id; } } ``` ::: :::section{.summary} ## Conclusion * Serialization in java involves converting an object's state into a byte stream, while deserialization reverses this process by converting a byte stream back into an object. * In Java, serialization is achieved using the writeObject(Object obj) method, while deserialization is done using the readObject() method. * To ensure compatibility between serialized objects and loaded classes, we use the serialVersionUID attribute to track versions of a Serializable class. * If a parent class implements java.io.Serializable, its child objects are automatically serializable without implementing java.io.Serializable themselves. * If a class contains an object of another non-serializable class as a data member, the class as a whole cannot be serialized. * Static members of a class remain unaffected by serialization in java. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully