SCJP : Serializable Mock Exam Practice Questions
Questions no -1
What is the output for the below code ?
public class A {
public A() {
System.out.println("A");
}
}
public class B extends A implements Serializable {
public B() {
System.out.println("B");
}
}
public class Test {
public static void main(String... args) throws Exception {
B b = new B();
ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream("datafile"));
save.writeObject(b);
save.flush();
ObjectInputStream restore = new ObjectInputStream(new FileInputStream("datafile"));
B z = (B) restore.readObject();
}
}
options
A)A B A
B)A B A B
C)B B
D)A B
Correct answer is : A
Explanations :On the time of deserialization , the Serializable object not create new object. So constructor of class B does not called.
A is not Serializable object so constructor is called.
Questions no -2
What is the output for the below code ?
public class A {}
public class B implements Serializable {
A a = new A();
public static void main(String... args){
B b = new B();
try{
FileOutputStream fs = new FileOutputStream("b.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(b);
os.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
options
A)Compilation Fail
B)java.io.NotSerializableException: Because class A is not Serializable.
C)Run properly
D)Compilation Fail : Because class A is not Serializable.
Correct answer is : B
Explanations :It throws java.io.NotSerializableException:A Because class A is not Serializable.
When JVM tries to serialize object B it will try to serialize A also because (A a = new A()) is instance variable of Class B.
So thows NotSerializableException.
Questions no -3
What is the output for the below code running in the same JVM?
public class A implements Serializable {
transient int a = 7;
static int b = 9;
}
public class B implements Serializable {
public static void main(String... args){
A a = new A();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("test.ser"));
os.writeObject(a);
os. close();
System.out.print( + + a.b + " ");
ObjectInputStream is = new ObjectInputStream(new FileInputStream("test.ser"));
A s2 = (A)is.readObject();
is.close();
System.out.println(s2.a + " " + s2.b);
} catch (Exception x)
{
x.printStackTrace();
}
}
}
options
A)9 0 9
B)9 7 9
C)0 0 0
D)0 7 0
Correct answer is : A
Explanations :transient variables are not serialized when an object is serialized.
In the case of static variable you can get the values in the same JVM.
|