InterviewSolution
| 1. |
Transient keyword in Java |
|
Answer» The transient keyword in Java is a variable modifier. It finds its application in serializiation. During serialization, if we don’t want to write the state of the particular variable in the byte stream, we use the transient keyword. When the JVM comes up to the transient keyword, it ignores the original state of the variable and stores a default value of that data type i.e. 0 for int, 0 for byte, 0.0 for float,etc. As static variables are ALSO ignored by the JVM, there is no use of writing transient with them though this won’t generate an error. As final variables are directly SERIALIZED by their values, there is no use of making them transient ALTHOUGH this would not give a COMPILE time error. The transient keyword is useful for security and data hiding. It is a good practice to use the transient keyword with private access specification. An example program where the effect of the transient keyword during serialization and deserialization is shown below: import java.io.*; public class Example implements Serializable { int a = 1, b = 2; // instance variables transient int c = 3; // transient variable // transient is rendered affectless with static and final transient final int d = 4; transient static int e = 5; public static void main(String[] args) throws Exception { Example input = new Example(); // serialization FileOutputStream fo = new FileOutputStream("example_file.txt"); ObjectOutputStream obj = new ObjectOutputStream(fo); obj.writeObject(input); // de-serialization FileInputStream fi = new FileInputStream("example_file.txt"); ObjectInputStream o = new ObjectInputStream(fi); Example x = (Example)o.readObject(); System.out.println("a = " + x.a); System.out.println("b = " + x.b); System.out.println("c = " + x.c); System.out.println("d = " + x.d); System.out.println("e = " + x.e); } }The output of the program is: $javac Example.java $java Example a = 1 b = 2 c = 0 d = 4 e = 5We can notice that the transient variable c has been set to its default value i.e. 0 while there is no CHANGE in the final, static and the instance variables. |
|