3.object Serialization
3.object Serialization
Serialization
Object Serialization
import java.io.*;
class Xyz implements Serializable {
double d1; Try this demo first by declaring the
transient double d2; variable d2 as non-transient(delete the
static double d3; key word transient). Try again by
void m1() { declaring the variable d2
as transient and observe the
difference
class TransientExample1 {
public static void main(String [] args) throws IOException {
Xyz x = new Xyz();
x.d1=10.3;
x.d2=20.5;
x.d3=99.99;
x.m1();
FileOutputStream fx = new FileOutputStream("A1.xyz");
ObjectOutputStream ox = new ObjectOutputStream(fx);
ox.writeObject(x);
ox.flush();
}
}
import java.io.*;
class TransientExample2 {
public static void main(String [] args) {
try {
FileInputStream fx = new FileInputStream("A1.xyz");
ObjectInputStream ox = new ObjectInputStream(fx);
Xyz x = (Xyz) ox.readObject();
x.m1();
}
catch(Exception e) {
System.out.println(e);
}
}
}
• When you compile all the three source files viz. Xyz.java,
TransientExample1.java and TransientExample2.java and
execute first
TransientExample1 and then TransientExample2, you will
get the following output (from executing TransientExampl
e2):
• The value of d1 is :10.3
• The value of d2 is :20.5
• The value of d3 is :0.0