The question is sometimes asked as – Can we define a field as ‘static transient’ and ‘final transient’ field?
Yes, we can define a field as ‘static transient’. We don’t receive any error and compiler doesn’t complain. However, this is not useful as static fields are not serialized. Static variables belong to a class and not to any individual instance. Serialization is meant to persist the object’s state. Therefore, static fields are ignored during serialization.
Similarly, we can define a field as ‘final transient’. We don’t receive any for this as well. final variables participate in serialization directly by their values.
‘static transient’ field example
import java.io.*; class Student implements Serializable { int rollNo = 100; static transient int age = 25; } class SerializationExample { public static void main(String args[]) throws Exception { Student d1 = new Student(); System.out.println("Serialization started"); FileOutputStream fos = new FileOutputStream("test.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(d1); System.out.println("Serialization ended"); System.out.println("Deserialization started"); FileInputStream fis = new FileInputStream("test.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Student d2 = (Student) ois.readObject(); System.out.println("Deserialization ended"); System.out.println("rollNo: " + d2.rollNo); System.out.println("age: " + d2.age); } }
Output
Serialization started
Serialization ended
Deserialization started
Deserialization ended
rollNo: 100
age: 25
‘final transient’ field example
import java.io.*; class Student implements Serializable { int rollNo = 100; final transient int age = 25; } class SerializationExample { public static void main(String args[]) throws Exception { Student d1 = new Student(); System.out.println("Serialization started"); FileOutputStream fos = new FileOutputStream("test.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(d1); System.out.println("Serialization ended"); System.out.println("Deserialization started"); FileInputStream fis = new FileInputStream("test.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Student d2 = (Student) ois.readObject(); System.out.println("Deserialization ended"); System.out.println("rollNo: " + d2.rollNo); System.out.println("age: " + d2.age); } }
Output
Serialization started
Serialization ended
Deserialization started
Deserialization ended
rollNo: 100
age: 25
Summary
Declaration | Output |
int rollNo = 100; int age = 25; | rollNo: 100 age: 25 |
transient int rollNo = 100; int age = 25; | rollNo: 0 age: 25 |
transient int rollNo = 100; transient static int age = 25; | rollNo: 0 age: 25 |
transient final int rollNo = 100; transient int age = 25; | rollNo: 100 age: 0 |