Java - Exceptions - Interview Questions and Answers on NotSerializableException

Q1.  What is the problem with this code ?

class BuggyBread1 {

private BuggyBread2 buggybread2;

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
   objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Ans. Though we are trying to serialize BuggyBread1 object but we haven't declared the class to implement Serializable.

This will throw java.io.NotSerializableException upon execution.

Q2.  Will this code run fine if BuggyBread2 doesn't implement Serializable interface ?

class BuggyBread1 implements Serializable{

private BuggyBread2 buggybread2 = new BuggyBread2();

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
   objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Ans. No, It will throw java.io.NotSerializableException.

Q3. Which is the Parent Class of NotSerializableException class?

Ans.java.io.ObjectStreamException

Q4. What is the package name for NotSerializableException class?

Ans.java.io

Q5. Which interfaces are implemented by NotSerializableException?

Ans.[Serializable]