Monday, August 16, 2010

Serialization: SerialTest.java

Courtesy of Sun Web Learning Center


 1. import java.io.*;
 2.
 3. public class SerialTest{
 4.   public static void main(String[] args) {
 5.     Traveler t = new Traveler();
 6.     Traveler t2 = new Traveler();
 7.     t.x1 = 7; t.x2 = 7; t.x3 = 7;
 8.
 9.     System.out.println("Before: " + t.x1 + " " + t.x2 + " " + t.x3);
10.  
11.     try {
12.       ObjectOutputStream out =
               new ObjectOutputStream( new FileOutputStream("object.dat"));
13.       out.writeObject(t);
14.       out.close();
15.     } catch(Exception e){
16.       e.printStackTrace();
17.     }
18.  
19.     try {
20.       ObjectInputStream in =
               new ObjectInputStream( new FileInputStream("object.dat"));
21.       t2 = (Traveler) in.readObject();
22.       in.close();
23.     } catch(Exception e){
24.       e.printStackTrace();
25.     }
26.  
27.     System.out.println("After: " + t2.x1 + " " + t2.x2 + " " + t2.x3);
28.   }
29. }
30.
31. class Traveler implements Serializable {
32.   public static int x1 = 0;
33.   public volatile int x2 = 0;
34.   public transient int x3 = 0;
35. }

On line 27, what values are the printed for t2?


A 0 0 0
B 0 7 0
C 0 7 7
D 7 0 0
E 7 7 0
F 7 7 7

E is correct. Because static variables belong to the class and not to instances of a class, they are not serialized.

No comments:

Post a Comment