Java OCA OCP Practice Question 2065

Question

Given the following code:

import java.io.Serializable;
public class Person implements Serializable {
  protected transient String name;
  Person() { this.name = "NoName"; }
  Person(String name) { this.name = name; }
}

import java.io.*;
public class Student extends Person {
  private long studNum;
  Student(String name, long studNum) {
    super(name);//from w  w  w . ja  va  2  s.  com
    this.studNum = studNum;
  }

  public String toString() { return "(" + name + ", " + studNum + ")"; }

  private void writeObject(ObjectOutputStream oos) throws IOException {
      oos.defaultWriteObject();
      oos.writeObject("NewName");
  }

  private void readObject(ObjectInputStream ois)
                throws IOException, ClassNotFoundException {
      ois.defaultReadObject();
      name = (String) ois.readObject();
  }
}
import java.io.*;
public class Main {

  public static void main(String args[])
                      throws IOException, ClassNotFoundException {
    FileOutputStream outputFile = new FileOutputStream("storage.dat");
    ObjectOutputStream outputStream = new ObjectOutputStream(outputFile);
    Student stud1 = new Student("Java", 100);
    System.out.print(stud1);/*  w w  w.j  a v  a  2s. co m*/
    outputStream.writeObject(stud1);
    outputStream.flush();
    outputStream.close();

    FileInputStream inputFile = new FileInputStream("storage.dat");
    ObjectInputStream inputStream = new ObjectInputStream(inputFile);
    Student stud2 = (Student) inputStream.readObject();
    System.out.println(stud2);
    inputStream.close();
 }
}

Which statement about the program is true?.

Select the one correct answer.

(a) It fails to compile.
(b) It compiles, but throws an exception at runtime.
(c) It prints (Java, 100)(Java, 100).
(d) It prints (Java, 100)(NewName, 100).
(e) It prints (Java, 100)(NoName, 100).


(d)

Note

During serialization of a Student object, the string NewName is also serialized.

During deserialization, this string is read and assigned to the transient field name which had not been serialized.




PreviousNext

Related