What does the modifier transient in Java do?


An instance variable is marked transient to point the JVM to skip the actual variable once serializing the thing containing it.

This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.

Example

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);
   }
}

Notice that for a class to be serialized successfully, two conditions must be met

  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Updated on: 30-Jul-2019

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements