Code Pumpkin

Transient Keyword In Java

May 13, 2017
Posted by Dipen Adroja

The transient keyword in java is used on class attributes to indicate that serialization process of such class should ignore such attributes for any instance of that class. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type.

transient keyword plays an important role to meet security constraints. One use of transient keyword is not to serialize the variable whose value can be derived using other serialized objects or system such as age of a person, current date, etc. Practically we serialized only those fields which represent a state of instance, after all serialization is all about to save state of an object to a file. It is good habit to use transient keyword with private confidential fields of a class during serialization.

How to use transient keyword?

The modifier transient in java can be applied to field members of a class to turn off serialization on these field members. Every field marked as transient will not be serialized. You use the transient keyword to indicate to the java virtual machine that the transient variable is not part of the persistent state of an object. Below are some of the example of using transient keyword.

Let's have a Employee class with three attribute firstName, lastName, birthdate and age. Now here, the attribute age is something which can be derived from the attribute birthdate. So we will mark the age field as transient attribute and see how the serialization and de-serialization works.


package com.codepumpkin;

import java.util.Date;

public class Employee {
	
	private String firstName;	
	private String lastName;
	private Date birthdate;
    //We declared age as transient variable as this can be derived from birthdate
	private transient int age;
	
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public Date getBirthdate() {
		return birthdate;
	}
	public void setBirthdate(Date birthdate) {
		this.birthdate = birthdate;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

Now, lets serialize and de-serialize using below code:


try {
	ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("empInfo.ser"));
	Employee emp = new Employee();
	emp.setFirstName("Code");
	emp.setLastName("Pumpkin");
	emp.setAge(26);
	emp.setBirthdate(new Date(1991, 7, 20));
	// Serialize the object
	oos.writeObject(emp);
	oos.close();
} catch (Exception e) {
	System.out.println(e);
}

try
{
	ObjectInputStream ooi = new ObjectInputStream(new FileInputStream("empInfo.ser"));
	//Read the object back
	Employee readEmpInfo = (Employee) ooi.readObject();
	System.out.println(readEmpInfo.getFirstName());
	System.out.println(readEmpInfo.getLastName());
	System.out.println(readEmpInfo.getAge());
	System.out.println(readEmpInfo.getBirthdate());
	ooi.close();
} catch (Exception e)
{
	System.out.println(e);
}

We will get the below output:

Code
Pumpkin
0
Thu Aug 20 00:00:00 IST 3891

If we observe properly here, the age field doesn't serialized.

Transient keyword with final variable:

One more thing one should keep in mind is that when we use transient keyword against attribute which is final. The jvm will ignore the transient keyword and serialize the final value of the variable.

Lets Summarize:

  • Transient will turn of the serialization of the attribute of the class.
  • Transient should be used for attributes which can be derived from other attributes or if the attribute is secure/confidential we should use transient to avoid writing it to file.
  • Whenever attribute is evaluated as constant expression(final), JVM ignore the presence of transient keyword.

Happy Learning 🙂

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate â‚ą42 per Tree.



About the Author


Coder, Blogger, Wanderer, Philosopher, Curious pumpkin



Tags: , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 124
follow us in feedly

Like Us On Facebook