Java transient Keyword
In Java programming, the transient keyword plays a crucial role in serialization. Here’s everything you need to know about its usage and implications.
Purpose of transient Keyword in Java:
The transient keyword in Java is used to indicate that a field should not be serialized. Serialization is the process of converting an object into a sequence of bytes to store it persistently or to transmit it over a network. When an object is serialized, all of its fields are converted into a byte stream. However, there are scenarios where certain fields of an object should not be serialized. This is where the transient keyword becomes useful.
Usage of Transient
When you declare a field with the transient keyword in Java, it informs the Java runtime system that the field is not part of the persistent state of the object. This means that when the object is serialized, the transient field is not included in the serialization process. Instead, its value is ignored during serialization and reset to its default value (null, 0, or false) during deserialization.
When to Use Transient
You should use the transient keyword for fields that do not need to be saved when an object is serialized. Common examples include fields holding cached or temporary data, fields holding non-serializable objects, or fields that should not persist across serialization.
java.lang.Integer Class Example
import java.io.*;
class MyClass implements Serializable {
// Serializable fields
private String name;
// Transient field
private transient int age;
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
public void printDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age); // Transient field will be 0 after deserialization
}
public static void main(String[] args) {
MyClass obj = new MyClass("John", 30);
// Serialize the object
try {
FileOutputStream fileOut = new FileOutputStream("object.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
// Deserialize the object
try {
FileInputStream fileIn = new FileInputStream("object.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
MyClass newObj = (MyClass) in.readObject();
in.close();
fileIn.close();
System.out.println("Object deserialized successfully.");
newObj.printDetails(); // Print deserialized object details
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example:
- The name field is serialized because it is not marked as transient.
- The age field is marked as transient, so its value will not be saved during serialization and will be reset to 0 (default value for int) during deserialization.