Java OCA OCP Practice Question 1878

Question

Let's say we want to write an instance of Main to disk, having a name value of AA.

What is the value of name after this object has been read using the ObjectInputStream's readObject() method?

package mypkg; //  www  .  j av  a 2 s.  co  m
public class Main { 
   private String name = "A"; 
   private transient int sugar; 
   public Main() { 
      super(); 
      this.name = "B"; 
   } 
   { 
      name = "CC"; 
   } 
   public String getName() { return name; } 
   public void setName(String name) { 
      this.name = name; 
   } 
   public int getSugar() { return sugar; } 
   public void setSugar(int sugar) { 
      this.sugar = sugar; 
   } 
} 
  • A. B
  • B. AA
  • C. CC
  • D. None of the above


D.

Note

The Main class does not implement the Serializable interface; therefore, attempting to write the instance to disk, or calling readObject() using ObjectInputStream, will result in a NotSerializableException at runtime.

Option D is the correct answer.

If the class did implement Serializable, then the value of name would be AA, since none of the constructor, initializers, or setters methods are used on deserialization, making Option B the correct answer.




PreviousNext

Related