Transient Keyword In Java

Within Java, the transient keyword is a qualifier utilized in serialization, which involves transforming an object into a sequence of bytes. When a field is designated as transient within a class, it is omitted from this serialization process. Consequently, the value of the field will not be retained during object serialization. Instead, upon deserialization, it will be set to its default value, such as null for objects and 0 for integers.

Why use the transient keyword?

Utilizing the transient modifier with class data members can prevent their serialization. For instance, in a scenario where a program gathers a user's login credentials, but there is a need to avoid persisting the actual password in a file, the transient keyword becomes valuable. Upon encountering the transient keyword, the JVM disregards the initial object value, opting to store the default object value instead.

The transient attribute serves to safeguard confidential or dispensable information from being serialized.

During deserialization, transient fields revert to their default values.

Syntax:

Example

private transient variableName;
Example

transient private variableName;
Example

transient datatype variableName;

When to use the transient keyword?

  • It can be used in cases where data members are derived from other data members within the same instance of the class.
  • It can be applied to data members that do not represent the state of the object.
  • The data members of a non-serialized object or class can utilize a transient modifier.
  • Example of transient Keyword

Consider the instance below where we've created a class named Student containing two attributes: name and age. During object serialization, all values are serialized by default, yet we wish to exclude the age attribute from this process. To achieve this, we marked the age attribute as transient. Consequently, upon object deserialization, the transient variable will assume its default value. It is essential to highlight that the age field is purposely omitted from serialization, leading to its value being reset when deserialized.

Upon inspection, it is evident that the student's age is returning a value of 0 due to the fact that the age value was not serialized.

Example

Example

import java.io.*;

class Student implements Serializable {

    String name;

    transient int age; // This field won't be serialized

    Student(String name, int age) {

        this.name = name;

        this.age = age;

    }

}

public class Main {

    public static void main(String[] args) throws Exception {

        Student student= new Student("Peter", 25);

        // Serialize the object

        FileOutputStream fileOut = new FileOutputStream("student.ser");

        ObjectOutputStream out = new ObjectOutputStream(fileOut);

        out.writeObject(student);

        out.close();

        fileOut.close();

        // Deserialize the object

        FileInputStream fileIn = new FileInputStream("student.ser");

        ObjectInputStream in = new ObjectInputStream(fileIn);

        Student deserializedStudent = (Student) in.readObject();

        in.close();

        fileIn.close();

        // prints name and age to the console

        System.out.println("Name: " + deserializedStudent.name); // Prints Peter

        System.out.println("Age: " + deserializedStudent.age);   // Prints 0 (default value)

    }

}

Output:

Output

Name: Peter

Age: 0

Advantages of the transient Keyword

  • Protects Sensitive Data: Fields like passwords, security tokens, or personal information can be marked transient to prevent them from being serialized and exposed.
  • Prevents Serialization of Irrelevant Data: We can exclude fields that do not make sense to serialize (for example, calculated values or temporary caches), which can reduce the size of the serialized object.
  • Improves Performance: By skipping non-essential fields during serialization, the time and memory usage for serialization/deserialization can be improved.
  • Avoids Non-Serializable Dependencies: If a field references a non-serializable object (like a thread, socket, or stream), marking it transient allows the rest of the object to be still serialized.
  • Disadvantages of the transient Keyword

  • Loss of Data: Transient fields are not saved during serialization, so they will be null (for objects), 0 (for numbers), or false (for booleans) after deserialization unless manually restored.
  • Requires Manual Handling: If a transient field needs to be reinitialized or reconstructed after deserialization, we must handle it in code (for example, in the readObject method).
  • Can Cause Bugs if Misused: If a developer unintentionally marks a critical field as transient, it can lead to an incomplete object state and subtle bugs.
  • No Effect Without Serialization: The transient keyword only applies in the context of serialization. If we are not serializing objects, it has no effect.
  • Java transient Keyword MCQs

  1. What does the transient keyword indicate in Java?
  • It cannot be serialized
  • It can be serialized
  • It is a final variable
  • It is a static variable

Explanation: The transient keyword can be used with the data members of a class to avoid their serialization.

  1. Which of the following types can be marked as transient?
  • Primitive Types
  • Reference Types
  • String Types
  • Only 1 and 2

Explanation: In Java, the transient keyword can be used with any data type, such as int, String, or objects, to indicate that a field should be excluded from serialization.

  1. The transient keyword is primarily used for________?
  • For security reasons
  • For reducing the file size
  • For improving performance
  • All the above

Explanation: The transient keyword can be used with the data members of a class to avoid their serialization. For example, if a program accepts a user's login details and password, but we do not want to store the original password in the file. In such cases, we can use the transient keyword.

  1. Which of the following will not be serialized?
  • Static Variable
  • Transient Variable
  • Final Variable
  • All the above

Explanation:

Static fields are distinct from the object's state and do not require the use of the transient keyword in association with static variables.

When using the final keyword with variables, they are serialized directly based on their values. Therefore, marking a variable as both final and transient serves no purpose in serialization.

Hence, the answer transient variable will not be serialize.

  1. What happens to transient variables during serialization?
  • They are preserved
  • They are ignored
  • They become static
  • They are converted to default values

When an object is serialized, transient variables are excluded from the object's serialized form. The values of these variables are not saved in the serialized file or sent over during transmission. Upon deserialization, these variables are set to their default values.

Input Required

This code uses input(). Please provide values below: