×

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

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 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.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.