Java Transient Keyword
Java Transient Keyword
In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the
data of the instance as well as the type of data stored in that instance. Deserialization performs exactly
opposite operation. It converts the byte sequence into original object data. During the serialization, when
we do not want an object to be serialized we can use a transient keyword.
The transient keyword can be used with the data members of a class in order to avoid their serialization.
For example, if a program accepts a user's login details and password. But we don't want to store the
original password in the file. Here, we can use transient keyword and when JVM reads the transient
keyword it ignores the original value of the object and instead stores the default value of the object.
Syntax:
1. private transient <member variable>;
Or
1. transient private <member variable>;
If you deserialize the object, you will get the default value for transient variable.
PersistExample.java
1. import java.io.*;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. transient int age;//Now it will not be serialized
6. public Student(int id, String name,int age) {
7. this.id = id;
8. this.name = name;
9. this.age=age;
10. }
11. }
12. class PersistExample{
13. public static void main(String args[])throws Exception{
14. Student s1 =new Student(211,"ravi",22);//creating object
15. //writing object into file
16. FileOutputStream f=new FileOutputStream("f.txt");
17. ObjectOutputStream out=new ObjectOutputStream(f);
18. out.writeObject(s1);
19. out.flush();
20. out.close();
21. f.close();
22. System.out.println("success");
23. }
24. }
Output:
success
DePersist.java
1. import java.io.*;
2. class DePersist{
3. public static void main(String args[])throws Exception{
4. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
5. Student s=(Student)in.readObject();
6. System.out.println(s.id+" "+s.name+" "+s.age);
7. in.close();
8. }
9. }
Output:
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.
In this article, we have discussed use of transient keyword in Java, where to use transient keyword