How do you serialize an object in Java

In Java, serialization is a process of converting an object into a byte stream, which can then be easily stored in a file or sent over a network. The Java platform provides built-in support for serialization, allowing you to convert an object into a sequence of bytes representing its state.

To make a Java object serializable, the class of the object must implement the java.io.Serializable interface. This marks the class as capable of serialization. Here is a simple example:

import java.io.*; class Employee implements Serializable { private String name; private int id; public Employee(String name, int id) { this.name = name; this.id = id; } } public class Main { public static void main(String[] args) { Employee emp = new Employee("John Doe", 123); try { // Serialization FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(emp); out.close(); fileOut.close(); System.out.println("Serialized data is saved in employee.ser"); } catch (IOException i) { i.printStackTrace(); } } }

Java Serialization Object Serialization Java IO Serializable Interface Java Byte Stream