What Is Transient Variable In Java? Serialization Example - Java67

Pages

  • Home
  • core java
  • spring
  • online courses
  • thread
  • java 8
  • coding
  • sql
  • books
  • oop
  • interview
  • certification
  • free resources
  • best
What is transient variable in Java? Serialization Example What is a transient variable in Java? transient variable in Java is a variable whose value is not serialized during Serialization and which is initialized by its default value during deserialization, for example for object transient variable it would be null. This behavior can be customized by using a custom Serialized form or by using the Externalizable interface. A transient variable is used to prevent any object from being serialized and you can make any variable transient by using the transient keyword. You cannot make a local variable transient through and it's only the member variables which can be transient. As the name suggest their value is not saved as part of object's state so they are not really represent an object state even though they are member variables. They are mostly used for security purposes. A good example of transient variables are sensitive data which you don't want save like the password or any security or auth token. By making them transient and not persisting them you reduce the risk. By the way difference between transient and volatile variable in Java is a famous Java interview question but transient the variable is completely different than volatile variable which we have discussed in our post What is a volatile variable in Java. In the next section, we will see a complete example of serialization where we will first serialize an instance of Book class which implements Serializable and then de-serialize to see what is the value of the transient variable after deserialization?

How to use a transient variable in Java - Serialization Example

Here is a complete code example of Serialization in Java which demonstrates How to use a transient variable in Java program; transient variables are not serialized during Serialization process and initialize with default the value during deserialization.What is transient variable in Java? Serialization Example

Transient Keyword Example in Java

And, here is our complete Java program to demonstrate how to use a transient variable in Java: package test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * * Java program to demonstrate What is transient variable in Java and fact that the value of * transient variable is not serialized and during serialization it initialized with * default value of that data type. e.g. If a transient variable is Object than after * deserialization its value would be null. * * @author Javin */ public class TransientTest { public static void main(String args[]) { Book narnia = new Book(1024, "Narnia", "unknown", 2); System.out.println("Before Serialization: " + narnia); try { FileOutputStream fos = new FileOutputStream("narnia.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(narnia); System.out.println("Book is successfully Serialized "); FileInputStream fis = new FileInputStream("narnia.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Book oldNarnia = (Book) ois.readObject(); System.out.println("Book successfully created from Serialized data"); System.out.println("Book after seriazliation : " + oldNarnia); } catch (Exception e) { e.printStackTrace(); } } } /* * A class that implements a Serializable interface and has a transient variable. */ class Book implements Serializable{ private int ISBN; private String title; private String author; private transient int edition = 1; //transient variable not serialized public Book(int ISBN, String title, String author, int edition) { this.ISBN = ISBN; this.title = title; this.author = author; this.edition = edition; } @Override public String toString() { return "Book{" + "ISBN=" + ISBN + ", title=" + title + ", author=" + author + ", edition=" + edition + '}'; } } Output: Before Serialization: Book{ISBN=1024, title=Narnia, author=unknown, edition=2} Book is successfully Serialized Book successfully created from Serialized data Book after seriazliation : Book{ISBN=1024, title=Narnia, author=unknown, edition=0} If you look at this example of serializing Object in Java you will realize that value of transient variables is not serialized and persisted and during deserialization, those values are initialized with their default value which is zero in the case of the int variable. Since the constructor also didn't run during de-serialization it won't get the value provided during the constructor. In Summary, use transient variables carefully in Java.In general, transient variable are used for security purposes. For example, if an object contains a password field, marking it as transient ensures that the password is not stored when the object is serialized, reducing the risk of exposure. Other Java Articles you may like :
  • Top 10 Serialization interview questions in Java
  • Difference between HashMap and ConcurrentHashMap in Java
  • 10 Object-oriented design principles Java programmer should know
  • Difference between TreeSet and HashSet in Java
  • Top 10 Java Generics interview question and answers
  • Difference between TreeMap and TreeSet in Java
  • Difference between HashMap and ArrayList in Java
Thanks for reading this article so far. If you like my explanation of transient variables in Java and examples of how transient variables are used while serializing and de-serializing an object then please share it with your friends and colleagues.

6 comments:

  1. UnknownDecember 17, 2015 at 10:29 PM

    good example

    ReplyDeleteReplies
      Reply
  2. UnknownDecember 21, 2015 at 10:47 AM

    very nice example

    ReplyDeleteReplies
      Reply
  3. UnknownJune 15, 2016 at 10:30 PM

    thanks

    ReplyDeleteReplies
      Reply
  4. UnknownSeptember 14, 2016 at 4:05 AM

    Very good example, thanks

    ReplyDeleteReplies
      Reply
  5. VaibhavJanuary 13, 2017 at 10:43 PM

    Good Example.

    ReplyDeleteReplies
      Reply
  6. AnonymousJanuary 7, 2018 at 10:25 PM

    very nice

    ReplyDeleteReplies
      Reply
Add commentLoad more...

Feel free to comment, ask questions if you have any doubt.

Newer Post Older Post Home Subscribe to: Post Comments (Atom)

Recommended Courses

  • best python courses
  • best java courses
  • system design courses
  • best spring courses
  • best hibernate courses
  • best design pattern courses
  • best Linux courses
  • best JavaScript courses
  • best data structure and algorithms courses
  • Best Multithreading Courses
  • best MERN stack courses
  • Best Git courses
  • Best Microservice Courses
  • Best DevOps Courses
  • best MEAN stack Courses
  • free Java courses
  • free DSA courses
  • free sql courses
  • free Linux courses
  • Free Docker courses
  • free JUnit courses

Categories

  • .NET
  • abstract class
  • Affiliate marketing
  • After Effects
  • Agile
  • AI Tools
  • Amazon Web Service
  • android
  • Angular
  • Anonymous class
  • Ansible
  • apache camel
  • Apache kafka
  • Apache spark
  • app development
  • array
  • ArrayList
  • Artificial Intelligence
  • automation
  • aws
  • aws certification
  • Azure Certifications
  • backend development
  • bash
  • basics
  • beginners
  • best of java67
  • best practices
  • Big Data
  • binary tree
  • bit manipulation
  • black friday deals
  • Blockchain
  • BlockingDeque
  • books
  • Bootstrap
  • business analysis
  • ByteByteGo
  • C programming
  • C++
  • Career
  • ChatGPT
  • Chef
  • cloud certification
  • Cloud Computing
  • Code Example
  • Code Review
  • codecademy
  • Codemia
  • CodeRabbit
  • coding
  • coding exercise
  • Coding Interview
  • Coding Problems
  • Comparator
  • computer science
  • Computer Vision
  • concurrency tutorial
  • ConcurrentHashMap
  • core java
  • core java interview question answer
  • course review
  • Coursera
  • courses
  • crontab
  • CSS
  • Cyber Monday
  • Cyber Security
  • Data Analysis
  • data science
  • data structure and algorithm
  • Data Visualization
  • database
  • datacamp
  • date and time
  • debugging
  • deep learning
  • default methods
  • design pattern
  • DevOps
  • DevSecOps
  • Distributed Systems
  • Django
  • docker
  • double
  • Drawing
  • dyanmic programming
  • dynamic Programming
  • eBooks
  • Eclipse
  • EJB
  • enum
  • equals
  • error and exception
  • Ethical hacking
  • Excel
  • exception
  • Exponent
  • expressjs
  • FAANG
  • Figma
  • Firebase
  • flatmap
  • float
  • Flutter
  • free resources
  • freelancing
  • Frontend Masters
  • fun
  • Fundamental
  • fundamentals
  • Game development
  • garbage collection
  • general
  • Generics
  • gifts
  • git and github
  • golang
  • Google Cloud Certification
  • Google Cloud Platform
  • Gradle
  • grails
  • graph
  • graphic design
  • grep
  • Groovy
  • gRPC
  • Hadoop
  • HashMap
  • HashSet
  • haskell
  • Hibernate
  • Hibernate interview Question
  • homework
  • HTML
  • HTTP
  • HttpClient
  • i
  • interface
  • Internet of Things (IoT)
  • interview
  • interview questions
  • IT Certification
  • J2EE
  • Jackson
  • java
  • Java 5 tutorial
  • java 7
  • Java 8
  • java 9
  • java basics
  • Java Certification
  • Java collection tutorial
  • java concurrency tutorial
  • java design pattern
  • Java Enum
  • Java file tutorials
  • Java Functional Programming
  • Java Installation Guide
  • Java Interview Question
  • Java interview questions
  • Java IO interview question
  • java io tutorial
  • java map tutorials
  • java modules
  • Java Multithreading Tutorial
  • Java networking tutorial
  • Java Operator tutorial
  • Java programming Tutorial
  • Java String tutorial
  • Java7
  • JavaScript
  • JavaScript Interview Question
  • JavaScript Tutorial
  • JDBC
  • JEE Interview Questions
  • Jenkins
  • JMS
  • JPA
  • jQuery
  • JSON
  • JSP
  • JSP Interview Question
  • JSTL
  • JUnit
  • JVM
  • Keras
  • keystore
  • Kotlin
  • kubernetes
  • lambda expression
  • Laraval
  • learning
  • linked list
  • Linux
  • Log4j
  • logging
  • Lombok
  • LSAT
  • Mac OS X
  • machine learning
  • Mathematics
  • Matlab
  • Maven
  • MERN stack
  • Messaging
  • Microservices
  • Microsoft
  • Microsoft Azure Platform
  • Microsoft Excel
  • Microsoft Power BI
  • Mockito
  • MongoDB
  • MysQL
  • MySQL tutorial example
  • nested class
  • neural network
  • Next.js
  • NFT
  • NLP
  • Node.js
  • nslookup
  • object oriented programming
  • OCAJP
  • OCMJEA
  • OCPJP
  • offers
  • Oracle
  • Perl
  • personal development
  • Photoshop
  • PHP
  • pluralsight
  • PostgerSQL
  • postman
  • Powerpoint
  • programmers
  • programming
  • programming problems
  • Project Management
  • projects
  • Prompt Engineering
  • Python
  • Pytorch
  • Quarkus
  • questions
  • Queue
  • R programming
  • React
  • React Hooks
  • react native
  • Record
  • Recursion
  • Redux
  • regular expression example
  • REST tutorials
  • Review
  • RoadMap
  • Ruby
  • Salesforce
  • SAT
  • Scala
  • Scala Interview Questions
  • Scanner
  • scripting
  • Scrum
  • Scrum Master Certification
  • Selenium
  • SEO
  • Serialization
  • Servlet
  • Servlet Interview Questions
  • Set
  • shell scripting
  • smart contracts
  • Snowflake SnowPro Certification
  • soft link
  • soft skills
  • software architecture
  • Solaris
  • Solidity
  • Sorting Algorithm
  • Spark
  • spring boot
  • Spring Certification
  • spring cloud
  • spring data jpa
  • spring framework
  • spring interview question
  • spring mvc
  • spring security
  • sql
  • SQL interview Question
  • SQL Joins
  • SQL SERVER
  • ssl
  • Static
  • Statistics
  • Stream
  • String
  • Struts
  • Swift
  • swing
  • switch case
  • system design
  • Tableau
  • Tailwind
  • TensorFlow
  • ternary operator
  • testing
  • thread
  • thread interview questions
  • Time series analysis
  • Tips
  • tomcat
  • tools
  • tree
  • TreeMap
  • troubleshooting
  • TypeScript
  • Udacity
  • Udemy
  • UI and UX Design
  • UML
  • unit testing
  • Unity 3D
  • Unix
  • unreal engine
  • Video Editing
  • Vuejs
  • web design
  • web development
  • web scrapping
  • Web Service
  • Whizlabs
  • Wix
  • xml
  • YAML
  • ZTM Academy

Best System Design and Coding Interview Resources

System Design & Interview Prep

  • ByteByteGo Lifetime Plan (50% OFF)
  • Codemia Lifetime Plan (60% OFF)
  • Exponent Annual Plan (70% OFF)
  • Educative Premium Plus (55% OFF)
  • DesignGurus All Course Bundle (55% OFF)
  • Everything Java Interview Bundle (50% OFF)
  • 101 Blockchain (50% OFF)
  • Vlad Mihalcea's High Performance Bundle (50% OFF)
  • Javarevisited Substack Subscription (50% OFF)
  • Head First Software Architecture (Book)

Search This Blog

Best Online Learning Resources and Platforms

  • Coursera Plus (40% OFF)
  • Datacamp Sale (50% OFF)
  • AlgoMonster Lifetime Plan (50% OFF)
  • Udemy Sale (80% OFF)
  • Baeldung (33% OFF)
  • LabEx Sale (50% OFF)
  • Codecademy Sale (60% OFF)
  • Udacity Sale (50% OFF)
  • ZTM Academy Sale (66% OFF)
  • Frontend Masters Deal
  • Whizlabs Deal (70% OFF)

Javarevisited

Loading...

Spring Interview Prep List

  • Spring Boot Interview questions
  • Spring Cloud Interview questions
  • Spring MVC Interview Questions
  • Microservices Interview questions
  • 10 Spring MVC annotations
  • Spring Boot Courses
  • Spring Framework Courses

Subscribe for Discounts and Updates

Follow

Interview Questions

  • core java interview questions
  • SQL interview questions
  • data structure interview question
  • coding interview questions
  • java collection interview questions
  • java design pattern interview questions
  • thread interview questions
  • hibernate interview questions
  • j2ee interview questions
  • Spring Interview Questions
  • object oriented programming questions

Followers

Blog Archive

  • ▼  2024 (192)
    • ▼  March (28)
      • How to enable or disable form elements using jQuer...
      • How to shuffle a List in Java? Collections.shuffle...
      • How to Compare Two Dates in Java? Check If They Ar...
      • What is transient variable in Java? Serialization ...
      • Difference between HashSet and HashMap in Java? An...
      • What is PATH and CLASSPATH in Java? Path vs ClassP...
      • Why is main method public, static, and void in Jav...
      • How to convert JSON String to Java Object using Gs...
      • Difference between var, val, and def in Scala? Exa...
      • 3 ways to convert String to JSON object in Java? E...
      • Difference between Correlated and Non-Correlated S...
      • How to sort ArrayList in Java? Examples
      • What is final modifier in Java? fina class, method...
      • Best way to Convert Integer to String in Java with...
      • How to create a ZIP File in Java? ZipEntry and Zip...
      • How to add JAR files in Eclipse Project's Build pa...
      • 5 Tips to Fix Exception in thread "main" java.lang...
      • 14 Enum Interview Questions and Answers for 1 to 2...
      • How to convert String to char in Java? Example Tut...
      • How to get current TimeStamp value in Java? Example
      • 5 Difference between String, StringBuffer, and Str...
      • Difference between include() and forward() methods...
      • Base64 Encoding and Decoding Examples in Java 8 an...
      • How Java achieves platform independence? Answer
      • 10 Difference between Struts 1.x and Struts 2.x f...
      • When You should Not use Microservice Architecture?...
      • Difference between static and instance member vari...
      • Top 10 Bash + UNIX Interview Questions and Answers

Privacy

  • Privacy Policy
  • Terms & Conditions

Popular Posts

  • 17 Free Java Programing Books for Beginners in 2025 - download, pdf and HTML
  • How to fix "illegal start of expression" error in Java? Example
  • Top 10 Websites to Learn JavaScript Coding for FREE in 2025 - Best of Lot
  • 5 Examples of Formatting Float or Double Numbers to String in Java
  • Top 10 Frequently asked SQL Query Interview Questions Answers

Subscribe

Get new posts by email:
Subscribe

Tag » What Is Transient In Java