Core Java

Transient variables in Java

Photo of Ilias KoutsakisIlias KoutsakisSeptember 22nd, 2014Last Updated: May 22nd, 2020
0 335 3 minutes read

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 theSerializable 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 thatwe 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 theSerializable 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
importjava.io.Serializable;
 
publicclassStudentimplementsSerializable {
     
    privateString name;
    privateintage;
    privatetransientintsemesters;
    privatetransientString comments;
     
    publicStudent(String name,intage,intsemesters, String comments) {
        this.name = name;
        this.age = age;
        this.semesters = semesters;
        this.comments = comments;
    }
     
    @Override
    publicString 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
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
 
publicclassSerializationExampleMain {
 
    publicstaticvoidmain(String[] args)throwsClassNotFoundException {
         
        // Create a student and populate the fields.
        Student student =newStudent("Bill",20,8,"No comments from me!");
        System.out.println("Before serialization:\n\t"+ student.toString());
         
         
        // Serialization of the object.
        try{
            FileOutputStream file =newFileOutputStream("student.ser");
            ObjectOutputStream out =newObjectOutputStream(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 =newFileInputStream("student.ser");
            ObjectInputStream in =newObjectInputStream(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 thetoString() method, we don’t get an exception, just the values that are given to these variables by Java. So an emptyint is automatically assumed to have a value of zero, while aString has a value ofnull 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

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ilias KoutsakisIlias KoutsakisSeptember 22nd, 2014Last Updated: May 22nd, 2020
0 335 3 minutes read
Photo of Ilias Koutsakis

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.

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.