Object Serialization and Java Transient Variables

string array javaJava programming consists of many variable data types used in different scenarios. I’is vital as a beginner to understand variables and data types.  As a programmer, you might not use some data types in the real world, but you should conceptually understand them.

Before we talk about Java transient variables, you need to know the concept of “serialization”. Serialization makes an object’s state persistent. Basically, it means that the state of the object is converted into a stream of bytes and stored in a file.  A programmer can also use deserialization, which gets the object’s state from serialized bytes. Serialization is a concept used prominently and frequently in online programming and hence it’s one of the more important Java topics for programmers to learn. For any object, which has to be transmitted over a network, it needs to be converted into bytes. Every class or interface must necessarily implement the serialization interface. It is a very efficient marker interface and does not have any methods.

If you’re learning Java, check out a beginner’s course at Udemy.com.

What does “transient” really mean for a programmer? You specify “transient” when you don’t want variables serialized. Every variable in an object is converted to a persistent state by default. However, a programmer might not want the object’s variables to persist in some cases as he does not have the necessity of transferring the program across the network and hence desires the state to be temporary. To achieve this, a programmer can declare the variables as transient and the object will not persist or be serialized. This is the “transient” keyword’s purpose.

Let’s take a look at a few examples that explains the transient variable better.

Program one:

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

class Store implements Serializable // including the serializable interface

{

String Name1; //Declaring necessary variables

transient String Age1; // Declared transient

String Occupation1;

public Store (String Name, String Age, String Occ) // Constructor method 

{

this.Name1 = Name;

this.Age1 = Age1;

this.Occupation = Occ;

}

public String toString(){

StringBuffer sbuff = new StringBuffer(39); // StringBuffer is declared

sbuff.append("Name : "); // Adding values to the StringBuffer variable

sbuff.append(this.Name1);

sbuff.append("Age : ");

sbuff.append(this.Age1);

sbuff.append("Occupation : ");

sbuff.append(this.Occ);

return sbuff.toString(); // Returning the Final String

}

}

public class Demo_Example

{

public static void main(String args[]) throws Exception

{

Store namStore = new Store("Jack","21","Student"); //Class object Creation

ObjectOutputStream obj = new ObjectOutputStream (newFileOutputStream("namStore"));

obj.writeObject(namStore);// writing the object values to outputstream

obj.close();

// Reading the stored values from the InputStream Variable

ObjectInputStream inb =new ObjectInputStream(newFileInputStream("namStore"));

Store nameStore1 = (Store)inb.readObject();

System.out.println(nameStore1);

}

}

Output

Name: Jack

Age :21

Occupation :Student

In the above example, Age is declared as a transient variable. Hence, the value of Age will not serialize.

Take a course at Udemy.com to learn Java programming from scratch

Program Two:

In the example shown here, two classes are created. These classes are Work and Persistent. A single member of the class Work is declared as transient and hence its value will not be serialized. If the object is deserialized again, it will return the default value for the given transient variable.

import java.io.Serializable;

public class Demo implements Serializable

{

int id;

String name,compan;

transient int pay;  //Declared transient it will not be serialized

public Demo(int id1, String comp, int payment) // Class constructor Declared

{

this.id = id1;

this.compan = comp;

this.pay=payment;

}

}

import java.io.*;

class Example{

public static void main(String args[])throws Exception

{

Demo obj1 =new Demo(312,"Google",5000);   // Declaring the class object

FileOutputStream fstream12=new FileOutputStream("fil.txt");

ObjectOutputStream out1=new ObjectOutputStream(fstream12);

out.writeObject(obj1);  // writing the object to the file

out1.flush();

System.out.println("success");  }

}

Output

success

Some programmers might find it difficult to differentiate between transient and volatile in Java. These are two very different keywords and a few noticeable differences among these two are:

  • The transient keyword is used along with instance variables in order to exclude them from getting serialized. In comparison, a volatile keyword is used to read the value of the variable directly from memory. It indicates to compilers and the program’s thread not to cache variable values.
  • The transient keyword is not usable along with the static keyword.
  • Transient variables are given a default value as the program initiates deserialization.
  • The transient keyword cannot be used with methods and constructors.

Usually, a programmer marks a variable as transient when the value can be easily calculated using another variable. For instance, you could have a field named “area” and its value can be derived using other fields such as “length” and “width.” Serializing this variable isn’t necessary since it’s calculated from other variables. Hence, “area” can be declared as a transient variable.

Learn everything you need to know about Java programming by taking a course at Udemy.com

PROGRAM three:

import java.io.Serializable;

class Exam implements serializable

{

Private Date curDate;

Private transient String dateValInString; /*this will not be saved because of the transient keyword */

Private void generatederivedValue()  /* this method will provide the date in format of 2 feb */

{

dateValInString= curDate.getDay() + “ ” + convertToStringMonth(curDate.getMonth());

}

}

In the above example when the object of the class is serialized, the variable dateValInString is not be saved because of the transient keyword. When thousands of objects need to be serialized, this saves the space.

Conclusion

It should be noted that the transient keyword can only be applied to the field or member variable. Static and transient keywords can be declared at the same time and the compiler won’t complain but it doesn’t make any sense to use it.Transient variables are always initialized with the default value at the time of deserialization and the assignment or restoration of the initialized value has to be managed by the application code. Overall, the Transient variable is very handy and functional but you must remember to use it very carefully in Java. Transient gives you some control over the process of serialization and provides you with a flexibility of excluding some object properties from the serialization process.