Talking about transient variable in Java

In the previous tutorial, you learned about Serialization that allows us to store the state of a Java object. All of the properties of the Java object are stored somewhere so that other processes can retrieve it to reuse.

But in reality, sometimes we need some of the attributes of a Java object that are not serialized, meaning that the state of those attributes is not preserved, their value will be the default value at startup when creating Java object.

OK, let’s take a look again the example we made in the tutorial about Serialization in Java.

Now that we have the Student object, we want the age attribute of this object to be not serialized. I will declare Student object as follows:

Now, I will run the code to serialized Student object:

Then read the student.txt file again:


Nói về biến transient trong Java

You see, the value of the age attribute is no longer 30 as before.


Add Comment