object serialization in java

object serialization in java

Object serialization in Java is a mechanism to convert an object into a byte stream, thereby making it possible to save the object to a file, transmit it over a network, or store it in a database. The reverse process, deserialization, converts the byte stream back into a copy of the object.

object serialization in java

Steps to Implement Serialization

  • 1. Implement the Serializable Interface: To serialize an object, the class must implement the `Serializable` interface. This is a marker interface, meaning it does not have any methods but indicates that the class can be serialized.
  • 2. Use ObjectOutputStream to Serialize the Object: The `ObjectOutputStream` class writes the object to an output stream. The object is converted into a byte stream and can be saved to a file or sent over a network.
  • 3. Use ObjectInputStream to Deserialize the Object: The `ObjectInputStream` class reads the object from an input stream, recreating it from the byte stream.

Step 1 : Define a Serializable Class
```java
import java.io.Serializable;

public class Employee implements Serializable {
    private static final long serialVersionUID = 1L; // Unique identifier for serialization
    private String name;
    private int id;
    
    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
}
```

Step 2 : Serialize the Object
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeDemo {
    public static void main(String[] args) {
        Employee emp = new Employee("John Doe", 12345);
        
        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 (IOException i) {
            i.printStackTrace();
        }
    }
}
```

Step 3 : Deserialize the Object
```java
import java.io.FileInputStream;
import java.io.IOException;
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();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("Employee class not found");
            c.printStackTrace();
            return;
        }
        
        System.out.println("Deserialized Employee...");
        System.out.println("Name: " + emp.getName());
        System.out.println("ID: " + emp.getId());
    }
}
```

Explanation of Key Points

  • serialVersionUID: This is a unique identifier for each class. It is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes that are compatible with respect to serialization. If no `serialVersionUID` is defined, Java will compute one at runtime, which might lead to `InvalidClassException` if the class has changed.
  • Transient Fields: If there are fields in the class that you do not want to serialize, you can mark them as `transient`. Transient fields are ignored during the serialization process.
  • ObjectOutputStream and ObjectInputStream: These classes are used to write and read the object. `ObjectOutputStream` writes the object to an output stream, and `ObjectInputStream` reads the object from an input stream.

Practical Considerations

  • Ensure that all objects within a class are also serializable.
  • Handle exceptions such as `IOException` and `ClassNotFoundException` to avoid runtime errors.
  • Be cautious with changes to the class structure after serialization, as it can lead to incompatibility issues.

This detailed explanation and example should provide a solid understanding of object serialization in Java.