What is transient keyword in Java?

The transient keyword in Java serves the purpose of indicating that a particular field should not undergo serialization. By default, when an object is serialized, all of its variables are converted into a persistent state. However, in certain exceptional scenarios, there might be a need to exclude specific variables from this serialization process. In such cases, you can declare those variables as transient. This instructs the JVM to ignore the original value of the transient variable and instead save the default value associated with its data type.

The primary objective of using the transient keyword is to prevent the persistence of certain variables during serialization. It is considered a good practice to utilize the transient keyword with private and confidential fields of a class when serialization is involved. A prime example where the use of the transient keyword is prominent is with a Thread field. Generally, there is no rationale for serializing a Thread object, as its state is highly specific to the flow of program execution.

import java.io.*; class Student implements Serializable { int id; String name; transient int age; Student(int id, String name,int age) { this.id = id; this.name = name; this.age = age; } }

Serializing and Deserialization of Object

Serialization in Java refers to the process of converting an object's state into a byte stream, which can be stored or transmitted. Deserialization, on the other hand, is the process of reconstructing an object from a serialized byte stream. This allows objects to be saved to disk, sent over networks, or stored in databases.

Serializing an Object
public class TestClass{ public static void main(String[] args) { try{ Student st = new Student(101,"John",10); FileOutputStream fos = new FileOutputStream("student.info"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(st); oos.close(); fos.close(); }catch(Exception e){ System.out.println(e); } } }
Deserialization of Object
public class TestClass{ public static void main(String[] args) { Student st = null; try{ FileInputStream fis = new FileInputStream("student.info"); ObjectInputStream ois = new ObjectInputStream(fis); st = (Student)ois.readObject(); }catch(Exception e){ System.out.println(e); } System.out.println(st.id); System.out. println(st.name); } }

When you try to deserialize, you wont get back the transient field "age" because its not serialized.


The transient keyword is used to indicate that a field should not be serialized when an object is converted into a byte stream, allowing the exclusion of specific variables from the serialization process.