Core Java

Transient variables in Java

In this post we are going to examine what a transient variable is in Java and learn how to use them in the right context. In order to do that we are going to also take a quick look into the Serializable interface and its usefulness. 

1. Object Serialization and “transient” variables

Serialization is a process where a Java object can be written in a file as a sequence of bytes, containing all the object’s data as well as the meta-data (class name, method names, etc). Essentially we can serialize an object and then deserialize it anywhere else (e.g. another computer, another part of the program) and be able to use it as a standard object. Serialization by itself is a simple procedure and we are including an example of it in the code that follows.

Transient is a keyword that we can use for a class variable, which means that we don’t want this specific variable to hold on to any data at all after the process of serialization. This is extremely important, because there are scenarios in which we have a large amount of variables containing data, which do not need to be saved after serialization (maybe we need to just save a couple of things after processing and all the relevant data have no use anymore).

Next, we are going to show an example of how the “transient” keyword affects data after serialization.

2. Serialization with transient variables example

We have created a simple Student class which extends the Serializable interface, containing two transient class variables. We are going to serialize and deserialize it in the same program, and the effect of the transient keyword will become very obvious.

Student.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.Serializable;
 
public class Student implements Serializable {
     
    private String name;
    private int age;
    private transient int semesters;
    private transient String comments;
     
    public Student(String name, int age, int semesters, String comments) {
        this.name = name;
        this.age = age;
        this.semesters = semesters;
        this.comments = comments;
    }
     
    @Override
    public String toString() {
        return "Name: " + name +
                ", age: " + age +
                ", semesters: " + semesters +
                ", comments: " + comments;   
    }
}

SerializationExampleMain.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
public class SerializationExampleMain {
 
    public static void main(String[] args) throws ClassNotFoundException {
         
        // Create a student and populate the fields.
        Student student = new Student("Bill", 20, 8, "No comments from me!");
        System.out.println("Before serialization:\n\t" + student.toString());
         
         
        // Serialization of the object.
        try {
            FileOutputStream file = new FileOutputStream("student.ser");
            ObjectOutputStream out = new ObjectOutputStream(file);
            out.writeObject(student);
            
            System.out.printf("\nStudent serialized and saved.\n\n");
            
            out.close();
            file.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
         
         
        // Deserialization of the object.
        try {
            FileInputStream file = new FileInputStream("student.ser");
            ObjectInputStream in = new ObjectInputStream(file);
            Student st = (Student) in.readObject();
             
            System.out.println("After serialization:\n\t" + st.toString());
             
            in.close();
            file.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

Output

1
2
3
4
5
6
7
Before serialization:
    Name: Bill, age: 20, semesters: 8, comments: No comments from me!
 
Student serialized and saved.
 
After serialization:
    Name: Bill, age: 20, semesters: 0, comments: null

Take notice, the class variables by themselves continue to exist, but they have no data associated with them, so when we try to print the student’s information by using the toString() method, we don’t get an exception, just the values that are given to these variables by Java. So an empty int is automatically assumed to have a value of zero, while a String has a value of null because it is an object.

3. Download the source code

This was an example of transient variables in Java.

Download
You can download the full source code of this example here: Transient variables in Java

Last updated on May 22nd, 2020

Ilias Koutsakis

Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button