Log in
updated 11:29 AM UTC, May 4, 2016

what is a transient variable? And give an example usage of the variable.

  • Written by Madhu V Rao
  • Published in Core Java

what is a transient variable? And give an example usage of the variable.

Ans: A transient variable is a variable that can not be serialized.
the transient keyword can be used to indicate the Java virtual machine that the variable is not part of the persistent state of the object.

This can be used in a scenario where only some of the fields in a class are required to be saved and others are actually dervied from the existing .


Example code:

class MyExample  implements Serializable
{
    private Date currentDate;
    private transient String dateValueInString;     // this will not be saved

   // This methos provides the date in the format 2 feb
    private void generatederivedValue()
    {
    dateValueInString = currentDate.getDay() + " " + convertToStringMonth(currentDate.getMonth());
    }
}

So when the object of the above class is serialized , the dateValueInString will not be saved.  This would help in saving space when thousands of the objects of this class are serialized.
At the time of deserialization , you can go ahead and call the generatederivedValue() method , you would need to add this to your readObject() method as below:

private void readObject(ObjectInputStream inputStream)
            throws IOException, ClassNotFoundException
{
     inputStream.defaultReadObject();
     generatederivedValue();
}   

This is one of the favorite interview questions and interviewer usually asks you a realtime usage of this variable. Think of a scenario where this can be used , like banking and finance , etc. Use your creativity. what Interviewer expects is a creative and sensible answer.


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest