ERROR - java.io.NotSerializableException

Error

java.io.NotSerializableException: while running the code.

Possible Causes

1.

Serializing an object of class which is not declared Serializable. 

Sample Code

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

}

2.

Serializing an object having another object which is not declared serializable.

Sample Code

class BuggyBread1 implements Serializable{
  private BuggyBread2 buggybread2 = new BuggyBread2();
    // BuggyBread2 is not serializable
   
    public static void main(String[] args){
       try {
 ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
             objectOutputStream.writeObject(buggybread1);
       } catch (Exception e) { 
               e.printStackTrace();
       }
    }


}


Possible Resolutions

1. Make sure that the Class is declared Serializable.
2. Make sure that the Classes for all composed objects should be decalred serializable

or 

Make sure that the references for the composed objects should be decalred transient if the corresponding class is not serializable.

class BuggyBread1 implements Serializable{
        transient 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) {
                  e.printStackTrace();
            }
      }
}