Java Serialization Example

Active10 months ago
  1. What Is Java Serialization
  2. Java Serialization Example
  3. Serialization Java Tutorial
  4. Java Serialization Example In Word
  5. Java Serializable Example

In Java, object serialization means representing an object as a sequence of bytes. The bytes includes the object's data and information. A serialized object can be written into a file/database, and read from the file/database and deserialized. This serialization and deserialization helps us in many scenarios like gaming, session state management etc. This is done using Object Streams in Java. Learn how to do this using Serializable interface in Java.

What is meant by 'object serialization'? Can you please explain it with some examples?

jacktrades
3,78211 gold badges45 silver badges77 bronze badges
WarriorWarrior
23.6k43 gold badges126 silver badges201 bronze badges

13 Answers

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.

TarkaDaalTarkaDaal
8,4597 gold badges30 silver badges48 bronze badges
Java Serialization Example

You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation).

It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.

In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.

You can also prevent some data in your object from being serialized by marking the attribute as transient.

Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases. To do this, you use one of the hidden features in java.

It is important to notice that what gets serialized is the 'value' of the object, or the contents, and not the class definition. Thus methods are not serialized.

Here is a very basic sample with comments to facilitate its reading:

When we run this program, the file 'o.ser' is created and we can see what happened behind.

If we change the value of: someInteger to, for example Integer.MAX_VALUE, we may compare the output to see what the difference is.

Here's a screenshot showing precisely that difference:

Can you spot the differences? ;)

There is an additional relevant field in Java serialization: The serialversionUID but I guess this is already too long to cover it.

codeforester
20.6k8 gold badges48 silver badges77 bronze badges
OscarRyzOscarRyz
148k99 gold badges350 silver badges525 bronze badges

Daring to answer 6 year old question, adding just a very high level understanding for people new to Java

What is Serialization?

Converting an object to bytes and bytes back to object (Deserialization).

when is serialization used?

When we want to Persist the Object.When we want the object to exist beyond the lifetime of the JVM.

Real World Example:

ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawl details will be serialized and sent to server where the details are deserialized and used to perform operations.

How serialization is performed in java.

  1. Implement java.io.Serializable interface (marker interface so no method to implement).

  2. Persist the object: Use java.io.ObjectOutputStream class, a filter stream which is a wrapper around a lower-level byte stream (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side).

    • writeObject(<<instance>>) - to write an object
    • readObject() - to read an serialized Object

Remember:

When you serialize an object, only the object's state will be saved, not the object's class file or methods.

When you serialized a 2 byte object, you see 51 bytes serialized file.

Steps how the object is serialized and de-serialized.

Answer for: How did it convert to 51 bytes file?

  • First writes the serialization stream magic data (STREAM_MAGIC= 'AC ED' and STREAM_VERSION=version of the JVM).
  • Then it writes out the metadata of the class associated with an instance (length of the class, the name of the class, serialVersionUID).
  • Then it recursively writes out the metadata of the superclass until it finds java.lang.Object.
  • Then starts with the actual data associated with the instance.
  • Finally writes the data of objects associated with the instance starting from metadata to actual content.

If you are interested in more in dept information about Java Serialization please check this link.

Edit : One more good link to read.

This will answer a few frequent questions:

  1. How not to serialize any field in class.
    Ans: use transient keyword

  2. When child class is serialized does parent class get serialized?
    Ans: No, If parent is not extending Serializable interface parents field don't get serialized.

  3. When parent is serialized does child class get serialized?
    Ans: Yes, by default child class also get serialized.

  4. How to avoid child class from getting serialized?
    Ans: a. Override writeObject and readObject method and throw NotSerializableException.

    b. also you can mark all fields transient in child class.

  5. Some system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable.
VdeXVdeX
6,7283 gold badges50 silver badges55 bronze badges

Serialization is taking a 'live' object in memory and converting it to a format that can be stored somewhere (eg. in memory, on disk) and later 'deserialized' back into a live object.

Tim Cooper
126k32 gold badges260 silver badges233 bronze badges
Kent BoogaartKent BoogaartJson
150k32 gold badges357 silver badges363 bronze badges

I liked the way @OscarRyz presents. Although here i am continuing the story of serialization which was originally written by @amitgupta.

Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.

Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything became fine.

Community
noquerynoquery
1,2051 gold badge12 silver badges16 bronze badges

My Two cents from my own blog:

Here is a detailed explanation of the Serialization: (my own blog)

Serialization:

Serialization is the process of persisting the state of an object. It is represented and stored in the form of a sequence of bytes. This can be stored in a file. The process to read the state of the object from the file and restoring it is called deserialization.

What is the need of Serialization?

In modern day architecture, there is always a need to store object state and then retrieve it. For example in Hibernate, to store a object we should make the class Serializable. What it does, is that once the object state is saved in the form of bytes it can be transferred to another system which can then read from the state and retrieve the class. The object state can come from a database or a different jvm or from a separate component. With the help of Serialization we can retrieve the Object state.

Code Example and explanation:

First let's have a look at the Item Class:

In the above code it can be seen that Item class implements Serializable.

This is the interface that enables a class to be serializable.

Now we can see a variable called serialVersionUID is initialized to Long variable. This number is calculated by the compiler based on the state of the class and the class attributes. This is the number that will help the jvm identify the state of an object when it reads the state of the object from file.

For that we can have a look at the official Oracle Documentation:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named 'serialVersionUID' that must be static, final, and of type long: ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.

If you have noticed there is another keyword we have used which is transient.

If a field is not serializable, it must be marked transient. Here we marked the itemCostPrice as transient and don't want it to be written in a file

Now let's have a look on how to write the state of an object in the file and then read it from there.

In the above we can see an example of serialization and deserialization of an object.

For that we used two classes. For serializing the object we have used ObjectOutputStream. We have used the method writeObject to write the object in the file.

For Deserializing we have used ObjectInputStream which reads from the object from the file. It uses readObject to read the object data from the file.

The output of the above code would be like:

Notice that itemCostPrice from deserialized object is null as it was not written.

We have already discussed the basics of Java Serialization in part I of this article.

Now let's discuss it deeply and how it works.

First let's start with the serialversionuid.

The serialVersionUID is used as a version control in a Serializable class.

If you do not explicitly declare a serialVersionUID, JVM will do it for you automatically, based on various properties of the Serializable class.

Java's Algorithm of Calculating serialversionuid (Read more details here)

  1. The class name.
    1. The class modifiers written as a 32-bit integer.
    2. The name of each interface sorted by name.
    3. For each field of the class sorted by field name (except private static and private transient fields: The name of the field. The modifiers of the field written as a 32-bit integer. The descriptor of the field.
    4. If a class initializer exists, write out the following: The name of the method, .
    5. The modifier of the method, java.lang.reflect.Modifier.STATIC, written as a 32-bit integer.
    6. The descriptor of the method, ()V.
    7. For each non-private constructor sorted by method name and signature: The name of the method, . The modifiers of the method written as a 32-bit integer. The descriptor of the method.
    8. For each non-private method sorted by method name and signature: The name of the method. The modifiers of the method written as a 32-bit integer. The descriptor of the method.
    9. The SHA-1 algorithm is executed on the stream of bytes produced by DataOutputStream and produces five 32-bit values sha[0..4]. The hash value is assembled from the first and second 32-bit values of the SHA-1 message digest. If the result of the message digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of five int values named sha, the hash value would be computed as follows:

Java's serialization algorithm

The algorithm to serialize an object is described as below:
1. It writes out the metadata of the class associated with an instance.
2. It recursively writes out the description of the superclass until it finds java.lang.object.
3. Once it finishes writing the metadata information, it then starts with the actual data associated with the instance. But this time, it starts from the topmost superclass.
4. It recursively writes the data associated with the instance, starting from the least superclass to the most-derived class.

Things To Keep In Mind:

  1. Static fields in a class cannot be serialized.

  2. If the serialversionuid is different in the read class it will throw a InvalidClassException exception.

  3. If a class implements serializable then all its sub classes will also be serializable.

  4. If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.

Eg:

Pritam BanerjeePritam Banerjee
11.8k6 gold badges53 silver badges73 bronze badges

Serialization means persisting objects in java. If you want to save the state of the object and want to rebuild the state later (may be in another JVM) serialization can be used.

Note that the properties of an object is only going to be saved. If you want to resurrect the object again you should have the class file, because the member variables only will be stored and not the member functions.

eg:

The Searializable is a marker interface which marks that your class is serializable. Marker interface means that it is just an empty interface and using that interface will notify the JVM that this class can be made serializable.

Andrew Thompson
155k29 gold badges172 silver badges363 bronze badges
SatheshSathesh
3,7606 gold badges27 silver badges41 bronze badges

Serialization is the process of converting an object's state to bits so that it can be stored on a hard drive. When you deserialize the same object, it will retain its state later. It lets you recreate objects without having to save the objects' properties by hand.

Cheese DaneishCheese Daneish

Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the 'in memory' java objects state are converted into a byte stream. This type of the file can not be understood by the user. It is a special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object.

The object to be serialized must implement java.io.Serializable Interface. Default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.

ObjectOutput interface extends the DataOutput interface and adds methods for serializing objects and writing bytes to the file. The ObjectOutputStream extends java.io.OutputStream and implements ObjectOutput interface. It serializes objects, arrays, and other values to a stream. Thus the constructor of ObjectOutputStream is written as:

Above code has been used to create the instance of the ObjectOutput class with the ObjectOutputStream( ) constructor which takes the instance of the FileOuputStream as a parameter.

The ObjectOutput interface is used by implementing the ObjectOutputStream class. The ObjectOutputStream is constructed to serialize the object.

Deserializing an Object in java

The opposite operation of the serialization is called deserialization i.e. to extract the data from a series of bytes is s known as deserialization which is also called inflating or unmarshalling.

ObjectInputStream extends java.io.InputStream and implements ObjectInput interface. It deserializes objects, arrays, and other values from an input stream. Thus the constructor of ObjectInputStream is written as:

Above code of the program creates the instance of the ObjectInputStream class to deserialize that file which had been serialized by the ObjectInputStream class. The above code creates the instance using the instance of the FileInputStream class which holds the specified file object which has to be deserialized because the ObjectInputStream() constructor needs the input stream.

SinduSindu

Serialization is the process of turning a Java object into byte array and then back into object again with its preserved state. Useful for various things like sending objects over network or caching things to disk.

Read more from this short article which explains programming part of the process quite well and then move over to to Serializable javadoc. You may also be interested in reading this related question.

Community
EskoEsko
24k10 gold badges48 silver badges77 bronze badges

Return the file as an Object : http://www.tutorialspoint.com/java/java_serialization.htm

Matteo Baldi
3,5239 gold badges25 silver badges41 bronze badges
Ran AdlerRan Adler

Java Object Serialization

Serialization is a mechanism to transform a graph of Java objects into an array of bytes for storage(to disk file) or transmission(across a network), then by using deserialization we can restore the graph of objects.Graphs of objects are restored correctly using a reference sharing mechanism. But before storing, check whether serialVersionUID from input-file/network and .class file serialVersionUID are the same. If not, throw a java.io.InvalidClassException.

Each versioned class must identify the original class version for which it is capable of writing streams and from which it can read. For example, a versioned class must declare:

serialVersionUID Syntax

serialVersionUID is essential to the serialization process. But it is optional for the developer to add it into the java source file. If a serialVersionUID is not included, the serialization runtime will generate a serialVersionUID and associate it with the class. The serialized object will contain this serialVersionUID along with other data.

Note - It is strongly recommended that all serializable classes explicitly declare a serialVersionUID, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected serialVersionUID conflicts during deserialization, causing deserialization to fail.

A Java object is only serializable. if a class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

  • A class must implement java.io.Serializable interface in order to serialize its object successfully. Serializable is a marker interface and used to inform the compiler that the class implementing it has to be added serializable behavior. Here Java Virtual Machine (JVM) is responsible for its automatic serialization.

    transient Keyword:java.io.Serializable interface

    While serializing an object, if we don't want certain data members of the object to be serialized we can use the transient modifier. The transient keyword will prevent that data member from being serialized.

    • Fields declared as transient or static are ignored by the serialization process.

    TRANSIENT & VOLATILE

  • Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.

  • Only objects that support the java.io.Serializable or java.io.Externalizable interface can be written to/read from streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.

Serializable Example For Files

Serializable Example Over Network

Distributing object's state across different address spaces, either in different processes on the same computer, or even in multiple computers connected via a network, but which work together by sharing data and invoking methods.

@see

YashYash
5,3991 gold badge34 silver badges49 bronze badges

|*| Serializing a class : Converting an object to bytes and bytes back to object (Deserialization).

|=> Object-Serialization is process of converting the state of an object into steam of bytes.

  • |-> Implement when you want the object to exist beyond the lifetime of the JVM.
  • |-> Serialized Object can be stored in Database.
  • |-> Serializable-objects cannot be read and understood by humans so we can acheive security.

|=> Object-Deserialization is the process of getting the state of an object and store it into an object(java.lang.Object).

  • |-> Before storing its state it checks whether serialVersionUID form input-file/network and .class file serialVersionUID are same.
    &nbsp&nbspIf not throw java.io.InvalidClassException.

|=> A Java object is only serializable, if its class or any of its superclasses

  • implements either the java.io.Serializable interface or
  • its subinterface, java.io.Externalizable.

|=> Static fields in a class cannot be serialized.

|=> If you do not want to serialise a variable of a class use transient keyword

|=> If a class implements serializable then all its sub classes will also be serializable.

|=> If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case,
NotSerializableException is thrown at runtime.

Pang
7,25916 gold badges68 silver badges108 bronze badges
Sujay U NSujay U N

protected by CommunityMay 30 '14 at 22:39

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged javaserializationobject-serialization or ask your own question.

Active1 year, 2 months ago

What is the Java analogue of .NET's XML serialization?

Raedwald
28.8k23 gold badges100 silver badges171 bronze badges
Dmitry ShechtmanDmitry Shechtman
3,1784 gold badges22 silver badges25 bronze badges

closed as off-topic by Samuel LiewSep 27 '18 at 9:51

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • 'Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.' – Samuel Liew
If this question can be reworded to fit the rules in the help center, please edit the question.

11 Answers

2008 AnswerThe 'Official' Java API for this is now JAXB - Java API for XML Binding. See Tutorial by Oracle. The reference implementation lives at http://jaxb.java.net/

2018 Update Note that the Java EE and CORBA Modules are deprecated in SE in JDK9 and to be removed from SE in JDK11. Therefore, to use JAXB it will either need to be in your existing enterprise class environment bundled by your e.g. app server, or you will need to bring it in manually.

CheekysoftCheekysoft

What Is Java Serialization

27.2k17 gold badges63 silver badges82 bronze badges

XStream is pretty good at serializing object to XML without much configuration and money! (it's under BSD license).

We used it in one of our project to replace the plain old java-serialization and it worked almost out of the box.

Boern
3,5173 gold badges35 silver badges56 bronze badges
Barak SchillerBarak Schiller

You may want to look at the Simple XML Serialization project. It is the closest thing I've found to the System.Xml.Serialization in .Net.

Basil Bourque
137k38 gold badges452 silver badges643 bronze badges
ARKBANARKBAN
1,9514 gold badges18 silver badges22 bronze badges

JAXB is part of JDK standard edition version 1.6+. So it is FREE and no extra libraries to download and manage.A simple example can be found here

XStream seems to be dead. Last update was on Dec 6 2008.Simple seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.

so_mvso_mv
3,2544 gold badges25 silver badges39 bronze badges

Worth mentioning that since version 1.4, Java had the classes java.beans.XMLEncoder and java.beans.XMLDecoder. These classes perform XML encoding which is at least very comparable to XML Serialization and in some circumstances might do the trick for you.

If your class sticks to the JavaBeans specification for its getters and setters, this method is straightforward to use and you don't need a schema. With the following caveats:

  • As with normal Java serialization
    • coding and decoding run over a InputStream and OutputStream
    • the process uses the familar writeObject and readObject methods
  • In contrast to normal Java serialization
    • the encoding but also decoding causes constructors and initializers to be invoked
    • encoding and decoding work regardless if your class implements Serializable or not
    • transient modifiers are not taken into account
    • works only for public classes, that have public constructors

For example, take the following declaration:

Executing this code:

Would result in the following file:

MishaxMishax
2,7815 gold badges27 silver badges54 bronze badges

XMLBeans works great if you have a schema for your XML. It creates Java objects for the schema and creates easy to use parse methods.

John MeagherJohn Meagher
13k13 gold badges48 silver badges56 bronze badges

If you're talking about automatic XML serialization of objects, check out Castor:

Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more.

TheoTheo
116k16 gold badges121 silver badges161 bronze badges

Usually I use jaxb or XMLBeans if I need to create objects serializable to XML. Now, I can see that XStream might be very useful as it's nonintrusive and has really simple api. I'll play with it soon and probably use it. The only drawback I noticed is that I can't create object's id on my own for cross referencing.

@Barak Schiller
Thanks for posting link to XStream!

Bartosz BierkowskiBartosz Bierkowski
2,6411 gold badge17 silver badges17 bronze badges
Cheeso

Java Serialization Example

Cheeso
139k78 gold badges412 silver badges647 bronze badges

if you want a structured solution (like ORM) then JAXB2 is a good solution.

If you want a serialization like DOT NET then you could use Long Term Persistence of JavaBeans Components

Serialization Java Tutorial

The choice depends on use of serialization.

Andrew Thompson
155k29 gold badges172 silver badges363 bronze badges
m.genovam.genova

Java Serialization Example In Word

user4067649user4067649

Java Serializable Example

Not the answer you're looking for? Browse other questions tagged javaxmlserialization or ask your own question.