Home » Java programming language

Java ObjectInputStream readObject() Method with Example

ObjectInputStream Class readObject() method: Here, we are going to learn about the readObject() method of ObjectInputStream Class with its syntax and example.
Submitted by Preeti Jain, on April 04, 2020

ObjectInputStream Class readObject() method

  • readObject() method is available in java.io package.
  • readObject() method is used to read an object from this ObjectInputStream and read the object in terms of object of the class, the signature of the class, values of non-static fields of the class, etc.
  • readObject() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • readObject() method may throw an exception at the time of the reading object.
    • ClassNotFoundException: This exception may throw when the serialized object Class could not exist.
    • InvalidClassException: This exception may throw when the invalid class used by serialization.
    • StreamCorruptedException: This exception may throw when the operating information in the stream is not consistent.
    • IOException: This exception may throw when getting any input/output error while performing.


    public Object readObject();


  • It does not accept any parameter.

Return value:

The return type of the method is Object, it returns the Object read from the ObjectInputStream.


// Java program to demonstrate the example 
// of Object readObject() method of ObjectInputStream

import java.io.*;

public class ReadObjectClass {
 public static void main(String[] args) throws Exception {
  // Instantiates ObjectOutputStream , ObjectInputStream 
  // FileInputStream and FileOutputStream
  FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
  ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
  FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
  ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);

  // By using writeObject() method is to
  // write object to Serialized class
  obj_out_stm.writeObject(new DefaultObjectClass());

  // By using readObject() method is to
  // read an object from the Serialized class
  DefaultObjectClass def_obj = (DefaultObjectClass) obj_in_stm.readObject();

  // Using both readObject and defaultReadObject(); 
  System.out.println("obj_in_stm.readObject(): " + def_obj.str);

 static class DefaultObjectClass implements Serializable {
  String str = "Java World";
  private void readObject(ObjectInputStream obj_stm) throws IOException, ClassNotFoundException {
   // By using defaultReadObject() method is 
   // to read non-static fields of the present 
   // class from the ObjectInputStream


obj_in_stm.readObject(): Java World

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.