Object Serialization

Start course
1h 46m

In this course, we'll learn about the Java Input/Output subject.

Learning Objectives

  • API and Java I/O
  • OutputStream Class
  • InputStream Class
  • Reader Class
  • Writer Class
  • Serialization, Deserialization, and Non-Serializable objects

Intended Audience

  • Anyone looking to get Oracle Java Certification
  • Those who want to learn the Java Programming language from scratch
  • Java developers who want to increase their knowledge
  • Beginners with no previous coding experience in Java programming
  • Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams


  • No prior knowledge is required about the Java programming language
  • Basic computer knowledge

Hi there. In this lesson, we'll talk about Serialization and Deserialization. First of all, let's look at what serialization and de serialization mean. Serialization is to store the state of an object by converting it to ByteStreams. Deserialization on the other hand is the reverse of this process. That is, it's the process of using a ByteStream again to retrieve the real stored Java object. So, why do we need it?

This operation ensures the persistence of objects. If you remember, we said that Java is a platform-independent language. An object stored with serialization can be used in its original form on a different platform with deserialization because ByteStreams are platform-independent. For the serialization process, it is sufficient to implement the serializable interface in the java.io package. This class has no methods or properties. It simply declares that the class it applies to is serializable. If you remember, we talked about the Marker Interface in our previous videos. These interfaces do not have any function. They are only used to mark the class to which they are applied on a particular subject. 

Therefore, it is sufficient for a class that we want to serialize to implement the Serializable Interface. Also, if a class you're serializing is a subclass of a serialized class, you do not need to serialize it again. That is, subclasses of serialized class are automatically serialized as well. But serializing a subclass does not serialize the super class of that class. Finally, we use the object OutputStream class for serialization and the object InputStream class for deserialization. Yes, if you want, let's move on to Eclipse now and get some practice. First, I'll create a new package and class in the Java Input/Output project. I right click on the source folder and select the new class options. The package name can be serializationexample and the class name can be Car and I click the 'Finish' button. Okay, so the Car class will implement the Serializable Interface to serialization. After the implements keyword, I write the Serializable interface. 

Let's look at this class by pressing the 'Ctrl' key and clicking on it. As you can see, there is no method or field because this interface is a Marker interface. It only declares the classes which implement it as Serializable. Okay, let's continue. I'll create some fields in the Car class. String model, color; int year; boolean isAutomatic; Now I'll create the full constructor of this class, so I right click on the empty field here and select the source generate constructor using fields options and I'll select all fields and click the 'Generate' button. Okay, now the constructor is ready. Also, I will override the toString method of this class to print the elements on the console easily and I'll change the return part. 

Here, I will return fields of this class. return( "Model: " + this.model after the plus sign, + "Color: " + this.color after the plus sign again, + "Year: " + this.year and lastly, + "isAutomatic: " + this.isAutomatic;. Also we can put \n before the Color, Year and isAutomatic to go to the next line. Also, notice that the Car class is underlined in yellow. If we position the mouse here, we'll see the following warning. The serializable class Car does not declare a static final serialVersionUID field of type long. So, what is this serialVersionUID? You can actually think of it as an identification number. You specify an ID number for the class you want to serialize. Of course, it must be static and final and must be of long type. Later when deserializing, these ID numbers are checked and if they are not the same, you'll get an InvalidClassException error during the deserialization phase. If you select the Add generated serial version ID option here, an ID will be generated for you automatically. If you don't add this, your program will run without any problems. Okay, now we can write these properties into a file. I'll create a test class. 

I right click on the serializationexample package and select the new class options. The class name can be SerializationTest and I'll check the checkbox for the main method and click the 'Finish' button. Okay, first I will create an ArrayList type of the Car class and I'll add some cars to this ArrayList. ArrayList< car > carList = new ArrayList<>() and let's add some cars to this ArrayList. carList.add(new car()). The model of the first car can be Ferrari, its color can be Red, its year can be 2020 and the isAutomatic property can be false, and I'll copy this line and paste it below twice. The second car can be Mercedes, its color can be Black, its year can be 2021, and the isAutomatic property can be false. The last car can be BMW, its color can be Blue, its year can be 2022, and the isAutomatic property can be true. Now, let's write this array into a file as an object using the FileOutputStream and ObjectOutputStream classes. FileOutputStream fos = new FileOutputStream(). The file name can be cars.txt. I would also like to point out that the file extension is usually specified as a different extension in serialization processes. 

This is to prevent this file from being opened and its contents changed. So, here you can write, dat or ser or something else as an extension or it can stay as txt again. Let's continue now. Also to prevent errors, I use the throws declaration, throws IOException{. Okay, now I will create an object from the ObjectOutputStream class. ObjectOutputStream objectStream = new ObjectOutputStream(). As the constructor parameter, I write (fos). Now we can write the carList array as the object into the car.txt file. So, I write objectStream.writeObject(carList);. Also, I'll show a message to understand if the write operation is complete. System.out.println("The cars are written..."). And lastly, I will close the stream, objectStream.close(); Okay, so the serialization process is complete. Let's run and see. As you can see, the cars are written in the file. Thus, the serialization process is also completed. As you can see, it's no different from normal data writing. The only difference is that you implement the Serializable class into the class you want to serialize. Now, let's deserialize. Actually, this is reading data from the file. 

First, I will create a new class for this. So, I right click on the serializationexample package and select the new class options. The class name can be DeserializationTest and I will check the checkbox for the main method and click the 'Finish' button. Okay, first I'll create an object from the FileInputStream class. FileInputStream fis = new FileInputStream(). In parentheses, I write the name of the file ("cars.txt"); Also, I'll use the throws declaration again or you can use the try-catch blocks. Okay, now I will create an object from the ObjectInputStream class. ObjectInputStream objectStream = new ObjectInputStream(). And as the constructor parameter, I write the fis in parentheses (fis). Now, I'll read the file and assign it to an object. Object carObject = objectStream.readObject();. Also the readObject method may throw the ClassNotFoundException. For this reason, I'll add another throws declaration for the ClassNotFoundException. Okay, now we can write this object on the console. System.out.println(carObject); and lastly I will close the stream, objectStream.close. 

Okay, let's run it and see. As you can see, we have successfully read the data. Of course, if you notice there are square brackets that indicate that it's an array since we transfer the data into an ArrayList and save it that way. And every single car we add appears to be an element of that. If you want, let's print them in a more readable way with the for each loop. I'll convert this line to the comment line and let's create the for each loop. for(Car car : carObject) but the carObject is an object not an array. To convert it, I'll cast it to the ArrayList. Okay, in the loop I will print each element using the toString method of the Car class. System.out.println(car.toString()); and to separate each element from the other, I'll use one more println method again. Okay, let's run it again. As you can see, this time, we have printed it to the console more legibly and properly. Yes, that's how the serialization and deserialization work. Let's take a short break here, see you in the next lesson.


About the Author
Learning Paths

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics