We use the transient keyword in Java when we work with Serialization. For example, in cases where we want to avoid serializing some variables.
If we put the transient keyword in front of some variable, the JVM will ignore its value and use the default value for that type.
When to use transient keyword in Java?
Here are some examples when we want to use the transient keyword:
- We don’t want to serialize variable which value can be calculated based on some other variables or objects that we already serialize.
- We have some private data and don’t want to serialize for security reasons (social security number, bank account number…)
- We know that we will not need certain values in the future when we deserialize the object back.
Using Transient in Java
Let’s create a User class that implements the Serializable interface:
import java.io.Serializable; public class User implements Serializable { transient int userId; String name; public User(int userId, String name) { this.userId = userId; this.name = name; } }
Now let’s write the object into a byte stream and place it into the user1.txt file. We put the transient keyword in front of the userId field because we don’t want to save its value.
import java.io.* public class Test { public static void main(String args[]) { try { User user1 = new User(15, "Ryan"); //Write the object in a stream FileOutputStream outputStream = new FileOutputStream("user1.txt"); ObjectOutputStream out = new ObjectOutputStream(outputStream); out.writeObject(user1); out.flush(); // close the stream out.close(); } catch (Exception e) { System.out.println("Writing object to file failed. Message: " + e.getMessage()); } }
We saved the user1 object into a file with the name user1.txt. Now let’s deserialize it and print its values:
import java.io.*; public class Test { public static void main(String args[]) { try { //Read the object ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("user1.txt")); User user1 = (User) inputStream.readObject(); System.out.println(user1.userId + " " + user1.name); //close the stream inputStream.close(); } catch (Exception e) { System.out.println("Reading object from a file failed. Message: " + e.getMessage()); } } }
Output: 0 Ryan
Here, we got 0 as the value of the userId variable. That’s because we put the transient keyword. The JVM ignored it during the serialization and used the default for integer type, 0.
That’s it!