Java Transient Keyword: Preventing Serialization of Sensitive Data
Learn how to use the transient keyword in Java to prevent sensitive data from being serialized. This technique is particularly useful when you need to exclude certain fields, like passwords or temporary data, from the serialization process during object persistence.
Java Transient Keyword
Serialization in Java converts an object into a byte stream, which includes the data and type of the instance. Deserialization converts the byte stream back into the original object. During serialization, the transient keyword is used to avoid serializing certain fields.
Why Use the Transient Keyword?
The transient keyword can be used with class data members to prevent their serialization. For example, if a program stores a user's login details and password but you don't want to save the actual password, you can use the transient keyword. The JVM will store the default value of the object instead of the original value when it reads the transient keyword.
Syntax
private transient <member variable>;
Syntax
transient private <member variable>;
When to Use the Transient Keyword?
- Use
transientwith data members derived from other data members within the same class instance. - Use
transientfor data members that do not depict the state of the object. - Use
transientfor data members of a non-serialized object or class.
Example of Java Transient Keyword
Consider a class Student with three data members: id, name, and age. If you serialize the object, all values will be serialized. However, if you don't want to serialize the age value, you can declare it as transient. When the object is deserialized, the transient variable will have its default value.
PersistExample.java
import java.io.*;
public class Student implements Serializable {
int id;
String name;
transient int age; // Now it will not be serialized
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
class PersistExample {
public static void main(String args[]) throws Exception {
Student s1 = new Student(2023, "Sunil", 29); // Creating object
// Writing object into file
FileOutputStream f = new FileOutputStream("f.txt");
ObjectOutputStream out = new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
out.close();
f.close();
System.out.println("success");
}
}
Output
success
Now write the code for deserialization:
DePersist.java
import java.io.*;
class DePersist {
public static void main(String args[]) throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("f.txt"));
Student s = (Student) in.readObject();
System.out.println(s.id + " " + s.name + " " + s.age);
in.close();
}
}
Output
2023 Sunil 0
As seen, printing the age of the student returns 0 because the value of age was not serialized.
In this article, we discussed the use of the transient keyword in Java, when to use it, and its implementation in a Java program.