The process of saving and
object to a file is called Serialization. Strictly Serialization means the
process of converting java supported format object to network supported format
object OR Process of converting object into stream of bytes.
If a variable is declared as transient at the time to
serialization JVM ignores the value of that transient variable. Instead of
original value JVM saves default value. Hence transient means not to serialize.
Example:
while saving Account information permanently to a file, we are not allowed to
save password for security reasons, such type of variables we have to declare
by transient keyword.
We can serialize only serializable
objects violation leads to RuntimeException saying “NotSerializableException”.
An Object is said to be seriablizable if and only if the corresponding class
implements serializable interface.
Import
java.io.*;
public class TransientDemo implements Serializable{
int i=10;
int j=20;
public static void main(String args[]) throws
Exception{
TransientDemo t1 = new
TransientDemo();
System.out.println(t1.i +
"----------" + t1.j);
//Serialization Process
FileOutputStream fos = new
FileOutputStream("abc.txt");
ObjectOutputStream oos = new
ObjectOutputStream(fos);
oos.writeObject(t1);
//De-serialization Process
FileInputStream fis = new
FileInputStream("abc.txt");
ObjectInputStream ois = new
ObjectInputStream(fis);
ois.readObject();
TransientDemo t2 =
(TransientDemo) ois.readObject();
System.out.println(t2.i +
"--------" + t2.j);
}
}
Output: 10----------20
10----------20
Case 1: If
we won’t implement serializable interface we get RunTimeException
java.io.NonSerializableException.
Case 2: If
we won’t place “throws Exception” at method we get compile time exception
saying unreported exception must be caught or declared to be throws.
Case 3: We
should type cast readObject else we get error Incompatable type error.
Analysis:
Case 1:
int i = 10;
int j = 20; output: 10----20
10----20
Case 2:
int i = 10;
transient int j = 20; output: 10----20
10----0
Case 3:
transient static int i=10;
int j=20; output: 10----20
10----20
Transient is useless in case of static variable.
Static variables never part
of object state. Hence they are not participating in serialization process.
Declaring a static variable as transient is useless & there is not impact
Case 4:
transient final int i=10;
int j=20; output: 10----20
10----20
Declaring a final variable as transient is
useless and there is no impact.
Caesars Palace, Casino, Spa & Hotel - MapYRO
ReplyDeleteCasino at Caesars Palace, Casino, Spa & Hotel. 777 Casino Ave, Las 과천 출장샵 Vegas, NV 89109. 광명 출장샵 Get Directions. Directions · (702) 895-6646. 강릉 출장안마 Call Now 경상북도 출장샵 · More Info. Hours, 부산광역 출장마사지