CodeGym /Java Course /Module 2. Java Core /Serialization. The beginning.

Serialization. The beginning.

Module 2. Java Core
Level 16 , Lesson 0
Available

"You will recall that today we investigated saving objects to and reading them from a file?"

"Yes, we just saved to an output stream, an read from an input stream."

"Well done, Amigo. It's good to hear that you're noticing these details. Would you be able to complete the code so that it saves to and reads from a file?"

"Complete what?! Declare a FileInputStream and FileOutputStream and pass them to the save and load methods. There's nothing to be confused about here. Super simple."

"I'm happy for you. Now for a new topic: serialization."

Serialization is almost the same as what we just did, but much cooler and built right into the Java machine. The Java machine can store and load its objects. It doesn't even need the save and load methods to do it: All objects are stored inside the Java machine, and it has full access to them."

We just take the object and save it to a stream and read from a stream:

Code
public static void main(String[] args) throws Exception
{
 Cat cat = new Cat();

 //Save a cat to file
 FileOutputStream fileOutput = new FileOutputStream("cat.dat");
 ObjectOutputStream outputStream = new ObjectOutputStream(fileOutput);
 outputStream.writeObject(cat);
 fileOutput.close();
 outputStream.close();

 //Load a cat from file
 FileInputStream fiStream = new FileInputStream("cat.dat");
 ObjectInputStream objectStream = new ObjectInputStream(fiStream);
 Object object = objectStream.readObject();
 fiStream.close();
 objectStream.close();

 Cat newCat = (Cat)object;
}

"That's it?"

"Exactly. There's a very large and complex serialization mechanism that lets us save to a stream and read from a stream of almost any data type."

"Almost any. So not any data type?"

"Yes, the fact is that not all objects have the inherent ability to be saved. Some objects don't store all their data internally. Instead, they merely reference other objects and/or data sources. For example, the console (System.in), an input stream (InputStream), and other things."

That's why Java's creators came up with the special Serializable interface marker. It's called a marker, because it doesn't contain any data and methods. It's only used to "tag" or "mark" classes. If we believe that our class stores all its data internally, then we can mark it with implements Serializable.

Here's a «cat» example with support for serialization:

Code
class Cat implements Serializable
{
 public String name;
 public int age;
 public int weight;
}

When we try to serialize (save) an object, the Java machine checks whether it supports serialization: Does it implement the Serializable interface? If it does, then it saves the object. If not, then it throws an exception to indicate that serialization is impossible.
Here you need to understand that a serializable object must only consist of serializable objects.

"Well, that makes sense. You can't save the whole without saving its parts."

"Exactly."

"And what about ints, Strings, and ArrayLists?"

"They all support serialization. Java's creators took special care to make sure this happened. There shouldn't be any problems here."

Moreover, an object's type is saved when the object is serialized. Now you can save a reference to a Cat object in an Object variable. Everything will serialize and deserialize just fine.

"Deserialize?"

"Deserialization is the process of reversing serialization: reading and reconstructing an object from a stream/file."

"Ah, no more questions then."

Comments (9)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Daniel Ketcheson Level 28, Canada
12 December 2023
AAA explanations @ Lvl 1-5 AA explanations @ Lvl 6 A explanations @ Lvl 7 B explanations @ Lvl 8 Just skip to the articles @ Lvl.size() - 1
Oregano Level 24, Warsaw, Poland
25 May 2020
"Complete what?! Declare a FileInputStream and FileOutputStream and pass them to the save and load methods. There's nothing to be confused about here. Super simple." Oh well. I'm still confused :) and tasks from previous lesson were not simple at all
Fadi Alsaidi Level 34, Carrollton, TX, USA
30 May 2020
you can say that again. However, you reached this level and you know by now that sometimes some stuff just sticks later ..well at least in my case
Johannes Level 27, Centurion, Pretoria, South-Africa
23 April 2020
Tip: before continuing with the course, read the 2 articles they give at the end of this level. It explains nicely how serialization works. Instead of struggling through the exercises with minimum explanation beforehand. https://codegym.cc/groups/posts/112-serialization-and-deserialization-in-java and https://codegym.cc/groups/posts/113-introducing-the-externalizable-interface
Melody Ye Level 29, France, France
26 May 2023
Thanks, helped a lot!
manny9876 Level 34, Israel
3 October 2023
Thanks for the tip! Great idea, I recommend everyone do the same. The articles tend to be clearer then the explanations here.
Ivan Duka Level 22, Winnipeg, Canada
25 April 2019
OK, now I see it clearly. We were taught to do it manually so we can understand how it works inside. However, there is a standard way to do it. Super cool!
Jason Level 26, Rancho Cucamonga, United States
27 November 2019
If I am not mistaken I believe that saving things as text to file also allows saved files and shared with ease outside of Java
Daniel Walbolt Level 22, Waterville, United States
9 August 2020
You are not mistaken, however you usually don't want the users of your program to be able to fluently read the stored data of your files. In this sense, they could give themselves the best equipment in your game by just changing the names in the text file properly. I do not exactly know yet if Serializing an Object is a form of Encryption, but if it is, it is a much better way of saving than English to a text file.