×

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it.

Transient variable

By introducing the transitory keyword, we may construct a particular kind of variable called a transient variable. It is a specific kind of variable that, at the time of processing, has a non-serialized value. Transient variables are variables that are started by their default value during de-serialization.

In large part because of a transitory variable, an item cannot be reproduced. We are able to define any variable fleeting by utilising the transitory keyword.

Typically, the interviewer will inquire as to the distinction between a volatile and transient variable. In this way, the volatile and transient variables are distinct from one another. A volatile keyword is relevant to the accessibility of values that are updated by many threads during concurrent programming, whereas the transient keyword would be primarily used when serializing an object.

The keywords volatile and transient are both less frequently employed by programmers and less well-liked than public, static, or final.

We make advantage of the temporary keyword to keep instance variables out of the serialization process. We just use volatile keyword to tell the compiler to retrieve the state of the variables from main memory.

The temporary keyword cannot be used with static, while the volatile keyword can.

Let us understand how this works with an example program

File name: Transient.java

importjava.io.FileInputStream;  
importjava.io.FileOutputStream;  
importjava.io.ObjectInputStream;  
importjava.io.ObjectOutputStream;  
importjava.io.Serializable;  
  
//Initiating a class with name Transient for understanding the functionality of transient    //variable 
public class Transient {  
  
    //The below is the main method  
    public static void main(String args[]) {  
      
        Book newBook = new Book(1014, "Java and OOPs", "RS Aggarwal", 5);  
        System.out.println("The book before it is serialized: " + newBook);  
          
        //Leveraging try-catch methods
try {   
FileOutputStream stream1 = new FileOutputStream("newBook.ser");  
  
           ObjectOutputStream stream2 = new ObjectOutputStream(stream1);  
stream2.writeObject(newBook);  
  
stream1.close();  
stream2.close();  
  
            // Depicts the message for successfully serialized book 
System.out.println("Book is successfully Serialized ");  
    
FileInputStream inputStream1 = new FileInputStream("newBook.ser");  
  
  ObjectInputStream inputStream2 = new ObjectInputStream(inputStream1);  
  
           Book oldBook = (Book) inputStream2.readObject();  
  
inputStream1.close();  
inputStream2.close();  
  
            //Displays the successful messages  
System.out.println("The book has been created from serialized information");
System.out.println("The book just after the seriazliation is : " + oldBook);  )
  
        } catch (Exception e) {  
e.printStackTrace();  
        }  
  
    }  
  
  
}  
  
// create class Book that implements the Serializable interface and has a transient variable.  
  
class Book implements Serializable{  
    //Variable declaration is supposed to be done here
    privateint ISBN;    // every book has a unique ISBN number  
private String title;   // every book has title
private String author;  //every book has been written by an author  
private transient int edition = 1; // edition of the book, i.e., transient variable not serialized  
  
    //a variable is created with help of a constructor
public Book(intisbn, String ttl, String auth, int edition) {  
this.ISBN = isbn;  
this.title = ttl;  
this.author = auth;  
this.edition = edition;  
    }  
  
public String toString() {  
        return "Book" + " ISBN= " + ISBN + ", title=" + title + ", author=" + author + ", edition=" + edition + '}';  
    }  
  
}  

Output

The book before it is serialized: Book   ISBN= 1014,  title= Java and OOPs,  author= RS Aggarwal, edition=5
The book has been created from serialized information
The book just after the serialization is : Book ISNB=1014,  title= Java and OOPs, author = RS Aggarwal, edition= 0

The use of temporary keywords is crucial for observing security restrictions. There are many situations in real life where we don't want to store private information in a file. The transitory keyword can also be used to avoid serializing variables whose values can be estimated or deduced from other serialized objects or systems, such as a person's age, the current date, etc.

Practically, we only serialized the fields that represented an instance's state; after all, the entire point of serialization is to store an object's information to a file. Use of the transitory keyword with a class's private, confidential fields during serialization is a good practise.

Using the transient keyword alongside static variables is useless because static fields aren't a part of the object's state. There's no compilation error, though.

Declaring a final variable to be temporary serves no purpose because final variables are explicitly serialized by their values. However, there isn't a compile-time error.


Related Topics

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.