I was reading the SCJP6 book from Kathy Sierra and Bert Bates (one of the most prestigious books if you are pursuing the Oracle Certification for Java SE 6 Programmer) and I found a question that will blow your mind. Well, at least my reaction was something like “wtf! there must be an errata somewhere…”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.*; public class TestSer { public static void main(String[] args) { SpecialSerial s = new SpecialSerial(); try { ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream("myFile")); os.writeObject(s); os.close(); System.out.print(++s.z + " "); ObjectInputStream is = new ObjectInputStream( new FileInputStream("myFile")); SpecialSerial s2 = (SpecialSerial)is.readObject(); is.close(); System.out.println(s2.y + " " + s2.z); } catch (Exception x) {System.out.println("exc"); } } } class SpecialSerial implements Serializable { transient int y = 7; static int z = 9; } |
Which are true? (Choose all that apply.)
- A. Compilation fails
- B. The output is 10 0 9
- C. The output is 10 0 10
- D. The output is 10 7 9
- E. The output is 10 7 10
- F. In order to alter the standard deserialization process you would implement the readObject() method in SpecialSerial
- G. In order to alter the standard deserialization process you would implement the defaultReadObject() method in SpecialSerial
My answer was B but the correct answer is “C and F”. Ok, I missed the “F” one and the entire question but why “C” ?!?!?!
What the heck the guys behind exams and certifications think when they are creating evil questions like this one. Probably you know that static variables aren’t serialized, right? So, why SpecialSerial.z has 10 instead of 9 ? Because “z” is static and any SpecialSerial instance created or unserialized during the execution of this Java application will always have z = 10. 😉