Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - transient keyword



In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI).

While serializing an object of a class, if you want JVM to neglect a particular instance variable you need can declare it transient.

Syntax

public transient int limit = 55; // will not persist
public int b; // will persist

Example

In the following java program, the class Student has two instance variables name and age where, age is declared transient. In another class named ExampleSerialize we are trying to serialize and deserialize the Student object and display its instance variables. Since the age is made invisible (transient) only the name value is displayed.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Student implements Serializable{

   private static final long serialVersionUID = 1L;
   private String name;
   private transient int age;

   public Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public String getName() {
      return this.name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public int getAge() {
      return this.age;
   }
}
public class ExampleSerialize{
   public static void main(String args[]) throws Exception{
      Student std1 = new Student("Krishna", 30);
      FileOutputStream fos = null;
      ObjectOutputStream oos = null;
      FileInputStream fis = null;
      ObjectInputStream ois = null;

      try {
         fos = new FileOutputStream("/tmp/student.ser");
         oos = new ObjectOutputStream(fos);
         oos.writeObject(std1);

         fis = new FileInputStream("/tmp/student.ser");
         ois = new ObjectInputStream(fis);
         Student std2 = (Student) ois.readObject();
         System.out.println(std2.getName());
      } catch(IOException e) {
         oos.close();
         fos.close();
         ois.close();
         fis.close();    	  
      }
   }
}

Output

Krishna

Example

In the following java program, we're creating serializing and deserializing an employee object.

Employee

package com.tutorialspoint;

public class Employee implements java.io.Serializable {
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   
   public void mailCheck() {
      System.out.println("Mailing a check to " + name + " " + address);
   }
}

SerializeDemo

package com.tutorialspoint;

import java.io.*;
public class SerializeDemo {

   public static void main(String [] args) {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      
      try {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      } catch (IOException i) {
         i.printStackTrace();
      }
   }
}

The following SerializeDemo program instantiates an Employee object and serializes it to a file. When the program is done executing, a file named employee.ser is created.

DeserializeDemo

package com.tutorialspoint;

import java.io.*;
public class DeserializeDemo {

   public static void main(String [] args) {
      Employee e = null;
      try {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      } 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: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
   }
}

Output

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

Here are following important points to be noted −

  • The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

  • Notice that the return value of readObject() is cast to an Employee reference.

  • The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.

java_basic_syntax.htm
Advertisements