Java OCA OCP Practice Question 2069

Question

Given the following code:

import java.io.Serializable;
public class Person implements Serializable {
  protected transient String name;
  Person(String name) { this.name = name; }
}
public class Student extends Person {
  private static int numOfStudents;
  private long studNum;
  Student(String name, long studNum) {
    super(name);//from w  w  w  .  j ava 2 s  .  c  o m
    this.studNum = studNum;
    ++numOfStudents;
  }
  public String toString() {
    return "(" + name + ", " + studNum + ", " + numOfStudents + ")";
  }
}
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. jav a 2  s  .c o m*/
    outputStream.writeObject(stud1);
    outputStream.flush();
    outputStream.close();

    Student student = new Student("Javascript", 300);

    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, 1)(Java, 100, 1).
  • (d) It prints (Java, 100, 1)(null, 100, 2).
  • (e) It prints (Java, 100, 1)(null, 100, 1).


(d)

Note

The field name in the Person class is transient, and the field numOfStudents in the Student class is static.

During serialization of a Student object, neither of these fields are serialized.

After deserialization, the value of the field name is null, but the value of the static field numOfStudents has been incremented because a second Student object has been created.




PreviousNext

Related