What is Transient Keyword in Java

Beginner programmers often ask what is a transient keyword in Java.

Java 9 specification says:

Variables may be marked transient to indicate that they are not part of the persistent state of an object.

What does it mean? When to use transient variable in java?

If you don’t want to serialize (convert an object to a byte array) part of the object – just add Java transient keyword.

if you’ll deserialize a byte array back to the object this field will be null (field default value).

Let’s take a look at code examples.

Examples of Transient Variable in Java

Let’s create a class Car with 2 fields: name and color.

Note that I implemented  Serializable interface and added  serialVersionUID.

It’s a marker interface that says: “This object can be serialized”.

We override toString() method as well to see what’s inside of a deserialized object.

We can test serialization using this code:

This code contains 6 steps:

  1. Create a Car object
  2. Serialize it
  3. Write to file
  4. Read from file
  5. Deserialize it to new Car object
  6. Print newly created car

Output:

As you can see name and color fields has a value as expected.

Let’s mark color as Java transient variable.

And execute that code again.

Output:

As you see color is null.

That’s exactly how transient in Java work.

Each Java transient field will be ignored during serialization.

What is a Difference Between Transient and Volatile in Java

I was really surprised when I found this question…

The only one this is common for  volatile and  transient – they are both field modifiers.

Nothing else!

As you know  transient keyword is related to serialization and volatile relates to the concurrency.

I’ll talk about it in one of the future articles.

If you have any questions about transient  – ask me in comments.

1 Star2 Stars3 Stars4 Stars5 Stars
Loading...
Scroll Up