Monday, 26 September 2016

Java Tutorial : Java IO (Java ObjectOutputStream and ObjectInputStream) - Playlist

Java Tutorial : Java IO (Java ObjectOutputStream | Java Serialization)

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction to ObjectOutputStream

In Java, serialization is the process of converting an object's state into a binary stream of bytes so it can be saved to a file, persisted into a database, or transmitted across a network. The fundamental class that makes this possible is ObjectOutputStream from the java.io package.

How ObjectOutputStream Works

ObjectOutputStream is a processing stream that wraps around an existing low-level byte output stream, such as a FileOutputStream. It implements both the ObjectOutput and DataOutput interfaces, allowing it to write full Java objects as well as raw primitive data types directly into the byte stream.

Core Methods of ObjectOutputStream

  • writeObject(Object obj): The primary method used to serialize an object. It writes the class descriptor, class signature, and the non-transient, non-static field values into the destination stream.
  • Writing Primitive Types: Provides dedicated methods inherited from DataOutput like writeInt(int val), writeDouble(double val), writeBoolean(boolean val), and writeUTF(String str).
  • flush() and close(): Flushes buffered output bytes and releases underlying OS resources.

Important Serialization Rules

1. Must Implement Serializable: Any object passed into writeObject() must implement either java.io.Serializable or java.io.Externalizable. If it does not, the JVM throws a runtime NotSerializableException.

2. Static and Transient Fields: By default, ObjectOutputStream skips any field marked with transient or static, ensuring only instance state is persisted.

3. Handling Object Graphs: If the serialized object contains references to other objects, ObjectOutputStream serializes the complete graph of reachable objects automatically.

Related Tutorials from Ram N Java

Java Tutorial : Java IO (Java Serializable Interface)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=N44f0ePhMbo&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Java IO (Java Serializable Interface) 
Employee.java
import java.io.Serializable;

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

    public int getId()
    {
        return id;
    }

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

    public String getName()
    {
        return name;
    }

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

}
Refer: 
https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_Serializable_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_Serializable_App/JavaIODemo

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/77a722c38e027b0dc283350527400c69b6e8d643/BasicJava/JavaIODemo_Serializable_App/JavaIODemo/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Friday, 23 September 2016

    Java Tutorial : Java IO (Java Serialization_V5)

    🚀 Enjoying Java Tutorials?

    Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

    🔔 Subscribe to Ram N Java

    What is Java Serialization?

    In Java, Serialization is the process of converting the state of an object into a sequence of bytes. This byte stream can then be persisted into a file, stored in a database, or transmitted across a network to another JVM.

    The reverse process—recreating the actual Java object from that byte stream in memory—is called Deserialization.

    Core Classes and Interfaces

    Java provides built-in support for object persistence in the java.io package through several key components:

    • Serializable Interface: A marker interface (it has no methods or fields). A class must implement this interface to signal to the JVM that its instances can be safely serialized.
    • ObjectOutputStream: A high-level processing stream that converts Java objects into byte streams using its writeObject() method.
    • ObjectInputStream: Reads the raw byte stream and reconstructs the original object in memory using its readObject() method.

    Why Do We Need Serialization?

    • Persistence: Saves the exact state of objects to disk files or databases across application restarts.
    • Deep Copying: Allows cloning complex, deeply nested object graphs by writing to and reading from a byte array.
    • Network Communication & RMI: Facilitates transferring objects between different JVMs in distributed systems and microservices.

    Important Concepts to Remember

    • transient Fields: Fields marked with the transient keyword are excluded from serialization and receive default values upon deserialization.
    • static Fields: Static variables belong to the class rather than an individual instance, so they are never saved in the serialized byte stream.
    • serialVersionUID: A unique identifier that ensures class compatibility between the sender and receiver during deserialization.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=gMLRxweHfFA&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial : Java IO (Java Serialization_V5) 
    Java Tutorial : Java IO (Java Serialization_V5) 
    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial : Java IO (Java Serialization_V4)

    🚀 Enjoying Java Tutorials?

    Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

    🔔 Subscribe to Ram N Java

    Introduction to Getting Started with Java Serialization

    Serialization is one of the most essential building blocks of the Java IO framework. Whether you want to persist application state across restarts or transmit live objects over a network connection, getting started with serialization allows you to convert any supported Java object into a portable stream of bytes.

    How to Serialize an Object: Step-by-Step

    1. Implement the Serializable Interface

    Your class must implement java.io.Serializable. This is a marker interface with no abstract methods to implement, acting purely as an opt-in signal to the Java Virtual Machine.

    public class Student implements java.io.Serializable {
        private static final long serialVersionUID = 1L;
        private int id;
        private String name;
    
        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }

    2. Writing the Object to a Stream (Serialization)

    Use FileOutputStream wrapped inside an ObjectOutputStream to write the instance state to disk:

    try (FileOutputStream fos = new FileOutputStream("student.ser");
         ObjectOutputStream oos = new ObjectOutputStream(fos)) {
        
        Student student = new Student(101, "Ram");
        oos.writeObject(student);
        System.out.println("Object serialized successfully!");
    } catch (IOException e) {
        e.printStackTrace();
    }

    3. Reading the Object Back (Deserialization)

    To recreate the object instance in memory, wrap a FileInputStream with an ObjectInputStream and cast the returned object:

    try (FileInputStream fis = new FileInputStream("student.ser");
         ObjectInputStream ois = new ObjectInputStream(fis)) {
        
        Student student = (Student) ois.readObject();
        System.out.println("Deserialized student: " + student);
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

    Key Points to Keep in Mind

    • serialVersionUID: Always declare an explicit serialVersionUID to avoid class version mismatch errors during deserialization.
    • transient Fields: Use transient to omit sensitive values like passwords or tokens from the output byte stream.
    • Resource Management: Always close your streams (preferably using try-with-resources) to prevent resource leaks.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=HhzX0CWq2zU&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial : Java IO (Java Serialization_V4)
    Java Tutorial : Java IO (Java Serialization_V4)
    Java Tutorial : Java IO (Java Serialization_V4)
    Java Tutorial : Java IO (Java Serialization_V4)
    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial : Java IO (Java Serialization_V3)

    🚀 Enjoying Java Tutorials?

    Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

    🔔 Subscribe to Ram N Java

    Java Serialization Overview

    In Java, objects exist in heap memory as long as the JVM is running. But what happens when you need to store an object’s current state to a file, persist it into a database, or transfer it across the network to another system? This is where Java Serialization comes into play.

    Serialization vs. Deserialization

    • Serialization: The mechanism of translating an in-memory Java object into a platform-independent byte stream.
    • Deserialization: The reverse operation, where the byte stream is reconstructed back into a live Java object in memory.

    The Core Building Blocks

    1. The java.io.Serializable Interface

    A class must implement the java.io.Serializable marker interface to become serializable. Because it contains no methods or variables, it simply marks the class as eligible for conversion to a byte stream.

    2. ObjectOutputStream & ObjectInputStream

    The standard stream classes responsible for serialization and deserialization:

    • ObjectOutputStream.writeObject() writes the object state to an output stream.
    • ObjectInputStream.readObject() reconstructs the object from an input stream.

    3. transient and static Keywords

    • transient: Prevents specific instance fields from being serialized (restored to default values like null or 0).
    • static: Belongs to the class level rather than the instance, meaning static variables are not part of the serialized state.

    Why Use Java Serialization?

    • Data Persistence: Easily preserve object graphs on disk between application runs.
    • Network Communication: Essential for Java RMI (Remote Method Invocation) and distributed messaging.
    • Deep Copying: Create complete clones of complex object graphs with minimal boilerplate code.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=yE7a6Gi7x4Q&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial : Java IO (Java Serialization_V3) 
    Java Tutorial : Java IO (Java Serialization_V3) 
    Java Tutorial : Java IO (Java Serialization_V3) 
    Java Tutorial : Java IO (Java Serialization_V3) 
    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial : Java IO (Java Serialization_V2)

    🚀 Enjoying Java Tutorials?

    Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

    🔔 Subscribe to Ram N Java

    Understanding Java Serialization

    In object-oriented programming with Java, applications constantly create objects that reside in memory. However, when the program terminates, all those objects are lost. Java Serialization is the core mechanism that allows developers to save the state of an object into a portable byte stream, enabling long-term persistence and seamless data transfer across networks.

    Core Concepts of Serialization and Deserialization

    • Serialization: Converting the state of an active Java object into a platform-independent stream of bytes using ObjectOutputStream.
    • Deserialization: Recreating the exact in-memory Java object from the byte stream using ObjectInputStream.
    • Marker Interface: To mark a class as eligible for serialization, it must implement java.io.Serializable, a marker interface that contains no methods or fields.

    Why is Serialization Important?

    • State Persistence: Easily write object graphs to files or databases and reload them whenever needed.
    • Distributed Applications: Essential for transferring live objects across networks in Java RMI, socket programming, and microservices.
    • Caching & Deep Cloning: Store complex objects in memory caches or create deep clones without repetitive boilerplate code.

    Crucial Points to Keep in Mind

    Concept Behavior
    transient Fields Excluded from serialization; restored to default values (e.g., null, 0)
    static Fields Belong to the class definition rather than the object instance; never serialized
    serialVersionUID Ensures class compatibility during deserialization across different JVM versions

    Related Tutorials from Ram N Java


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=FlPbBN8VPeY&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial : Java IO (Java Serialization_V2) 
    Java Tutorial : Java IO (Java Serialization_V2) 
    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial : Java IO (Java Serialization_V1)

    🚀 Enjoying Java Tutorials?

    Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

    🔔 Subscribe to Ram N Java

    Java Serialization Explained

    Serialization is one of the core foundational features of Java IO. It provides a standard, platform-independent mechanism for converting the state of an object into a byte stream. This byte stream can be written to a file, stored in a database, or transmitted across network connections, making it vital for enterprise applications and distributed systems.

    How Java Serialization Works

    The serialization architecture in Java revolves around two complementary processes:

    • Serialization: Flattens an in-memory object graph into a sequential stream of binary bytes using ObjectOutputStream.writeObject().
    • Deserialization: Reads the binary byte stream and reconstructs the identical object graph back into heap memory using ObjectInputStream.readObject().

    Core Components of Serialization

    1. The java.io.Serializable Interface

    Classes must explicitly opt in to serialization by implementing java.io.Serializable. Because it contains no methods or variables, it acts as a marker interface that instructs the JVM runtime that objects of this class are safe to serialize.

    2. Exclusion with transient and static

    • transient: Prevents sensitive or temporary fields from being serialized. These fields will be initialized to their default values (e.g., null, 0) upon deserialization.
    • static: Belongs to the class rather than an object instance, meaning static variables are never saved into the serialized stream.

    3. serialVersionUID Compatibility

    The serialVersionUID constant is used to verify that the sender and receiver of a serialized object have loaded classes that are compatible with respect to serialization.

    Quick Reference Table

    Component Description
    Serializable Marker interface required for classes to be serializable
    ObjectOutputStream Writes object state to a byte stream via writeObject()
    ObjectInputStream Reconstructs objects from a byte stream via readObject()
    transient Omits fields from serialization

    Related Tutorials from Ram N Java


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=6RhAJWsKYCc&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial : Java IO (Java Serialization_V1) 
    Java Tutorial : Java IO (Java Serialization_V1) 
    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Thursday, 22 September 2016

    Java Tutorial : Java IO (Serialization and deserialization)- Playlist

    Java Tutorial : Java IO (Marker Interface)

    Java Tutorial : Java IO (DataStreams)

    Java Tutorial : Java IO (DataOutputStream DataInputStream Example)


    Click here to watch in Youtube : 
    https://www.youtube.com/watch?v=OeL1GLYw8-M&list=UUhwKlOVR041tngjerWxVccw

    DataOutputStreamDemo.java
    import java.io.DataOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class DataOutputStreamDemo
    {
    
        public static void main(String[] args) throws Exception
        {
            DataOutputStreamDemo dataOutputStreamDemo = new DataOutputStreamDemo();
            dataOutputStreamDemo.writePrimitiveData();
        }
    
        public void writePrimitiveData() throws IOException
        {
            DataOutputStream dataOutputStream = null;
            FileOutputStream fileOutputStream = null;
            try
            {
                fileOutputStream = new FileOutputStream("data.txt");
                dataOutputStream = new DataOutputStream(fileOutputStream);
                int[] intArray = { 100, 250, 440, 550, 900 };
    
                for (int j : intArray)
                {
                    dataOutputStream.writeInt(j);
                }
    
                System.out.println("Successfully written to \'data.txt\' file\n");
            }
            finally
            {
                if (dataOutputStream != null)
                {
                    /*
                     * Closing a DataOutputStream will also
                     * close the OutputStream instance to which
                     * the DataOutputStream is writing.
                     */
                    dataOutputStream.close();
                }
            }
    
        }
    }
    
    Output
    Successfully written to 'data.txt' file
    
    data.txt
    DataInputStreamDemo.java
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class DataInputStreamDemo
    {
    
        public static void main(String[] args) throws Exception
        {
            DataInputStreamDemo dataInputStreamDemo = new DataInputStreamDemo();
            dataInputStreamDemo.readPrimitiveData();
        }
    
        public void readPrimitiveData() throws IOException
        {
            FileInputStream fileInputStream = null;
            DataInputStream dataInputStream = null;
    
            try
            {
                fileInputStream = new FileInputStream("data.txt");
                dataInputStream = new DataInputStream(fileInputStream);
    
                while (dataInputStream.available() > 0)
                {
                    int intValue = dataInputStream.readInt();
                    System.out.println(intValue);
                }
    
            }
            finally
            {
                if (dataInputStream != null)
                {
                    /*
                     * Closing a DataInputStream will also close
                     * the InputStream instance from which the
                     * DataInputStream is reading.
                     */
                    dataInputStream.close();
                }
            }
    
        }
    
    }
    
    Output
    100
    250
    440
    550
    900
    
    
    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_DataInput_and_Output_Stream_Example_App.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_DataInput_and_Output_Stream_Example_App

    Bitbucket Link:
    https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_DataInput_and_Output_Stream_Example_App

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial : Java IO (DataInputStream and DataOutputStream)-Playlist

    Java Tutorial : Java IO (DataOutputStream)


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=INIpdcB6o0k&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial : Java IO (DataOutputStream) 
    Java Tutorial : Java IO (DataOutputStream) 
    Java Tutorial : Java IO (DataOutputStream) 
    Java Tutorial : Java IO (DataOutputStream) 
    Java Tutorial : Java IO (DataOutputStream) 
    DataOutputStreamDemo.java
    import java.io.DataOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class DataOutputStreamDemo
    {
    
        public static void main(String[] args) throws Exception
        {
            DataOutputStreamDemo dataOutputStreamDemo = new DataOutputStreamDemo();
            dataOutputStreamDemo.writePrimitiveData();
        }
    
        public void writePrimitiveData() throws IOException
        {
            DataOutputStream dataOutputStream = null;
            FileOutputStream fileOutputStream = null;
            try
            {
                fileOutputStream = new FileOutputStream("data.bin");
                dataOutputStream = new DataOutputStream(fileOutputStream);
    
                dataOutputStream.writeInt(125);
                dataOutputStream.writeFloat(150.45F);
                dataOutputStream.writeLong(9090);
                dataOutputStream.writeBoolean(true);
    
                System.out.println("Successfully written primitive data's to \'data.bin\' file\n");
            }
            finally
            {
                if (dataOutputStream != null)
                {
                    /*
                     * Closing a DataOutputStream will also
                     * close the OutputStream instance to which
                     * the DataOutputStream is writing.
                     */
                    dataOutputStream.close();
                }
            }
    
        }
    }
    
    Output
    Successfully written primitive data's to 'data.bin' file
    

    data.bin

    DataInputStreamDemo.java
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class DataInputStreamDemo
    {
    
        public static void main(String[] args) throws Exception
        {
            DataInputStreamDemo dataInputStreamDemo = new DataInputStreamDemo();
            dataInputStreamDemo.readPrimitiveData();
        }
    
        public void readPrimitiveData() throws IOException
        {
            FileInputStream fileInputStream = null;
            DataInputStream dataInputStream = null;
    
            try
            {
                fileInputStream = new FileInputStream("data.bin");
                dataInputStream = new DataInputStream(fileInputStream);
    
                int intValue = dataInputStream.readInt();
                float floatValue = dataInputStream.readFloat();
                long longValue = dataInputStream.readLong();
                boolean booleanValue = dataInputStream.readBoolean();
    
                System.out.println("intValue     = " + intValue);
                System.out.println("floatValue   = " + floatValue);
                System.out.println("longValue    = " + longValue);
                System.out.println("booleanValue = " + booleanValue);
            }
            finally
            {
                if (dataInputStream != null)
                {
                    /*
                     * Closing a DataInputStream will also close
                     * the InputStream instance from which the
                     * DataInputStream is reading.
                     */
                    dataInputStream.close();
                }
            }
    
        }
    
    }
    Output
    
    intValue     = 125
    floatValue   = 150.45
    longValue    = 9090
    booleanValue = true
    
    Refer:
    https://docs.oracle.com/javase/8/docs/api/index.html?java/io/DataOutputStream.html
    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_DataInputStream_DataOutputStream_App.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_DataInputStream_DataOutputStream_App

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java/src/8270b2c7cbb37f975ee9fc66e47a041db3aa4063/BasicJava/JavaIODemo_DataInputStream_DataOutputStream_App/?at=master

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Tutorials