×

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

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.