- Java Blogs -

Serialization of Java Objects to XML Using XML Encoder/Decoder

Introduction to Java

Java is one of the most widely used and important programming languages that became popular due to its robustness. Unlike other structured programming languages, Java is highly secure and supports re-usability concept. It is quite suitable for web-applications as the client-server environment is required for such applications. It was developed in 1991 by Sun Microsystem Inc. The initial name of Java was Oak and it was renamed in 1995 as Java.

Many versions of Java have been launched so far. In each of its new version, many features are added to make it more competing in the programming world. Not only web or desktop applications can be developed using Java instead hardware controlling software components can also be designed in Java and we can say that following listed applications can be developed in Java:

  • Desktop Applications
  • Mobile Operating System like Android
  • Embedded Systems
  • Robotics and Games
  • Web Applications or Websites

Features of Java

The reason due to which Java is popular is the features that it provides to applications. Most important features are its portability and security. The features that are provided by Java are:

  • Simple – Java can be learned quickly because of its simpler syntax and concepts. If you have basic knowledge of C++ programming concepts then it is easy for you to switch to Java.
  • Object-Oriented – Everything in Java is defined with the help of objects. So, Java is an object-oriented programming language that simplifies the program development and maintenance.
  • Robust – Java has robust programming structure with excellent memory management, automatic garbage collection facility, best exceptional handling mechanism etc.
  • Platform Independent – Java is platform independent where write a single program in Java and run anywhere on different platforms.
  • Secure – The applications written in Java are highly secure and this is the reason why it is used by the organizations worldwide.
  • Multi-Threading – We can define multiple threads together in Java for any simple or complex tasks to complete it more efficiently in less time.
  • Architectural Neutral – Java has zero implementation-dependent features so it is defined as the architectural neutral programming language.
  • Portable – Java is portable because Java code can be taken to any platform in the form of bytecodes.
  • High Performance – Java is must faster as compared to traditional programming languages and easy to maintain too.

Apart from the above-mentioned features, Java has also added many new features like enhanced productivity, Lambda Expression, Streams, Script etc. Improved polyglot programming is supported by Java positively; security and performance have also been improved in its new versions.

Read: How to Convert Char to Int in Java

Serialization and Deserialization in Java

Through Serialization concept we can convert Java objects into bytes that are persisted to discs or database or it can be sent through streams. There is an interface named Serializable in Java that adds a serializable behavior to the class. Serialization and Deserialization in Java Following packages are provided by Java to serialize and deserialize the objects:

  • io.serializable
  • io.Externalizable
  • object input stream
  • objectOutputStream

If you do not want to make any field part of object state then you can declare it either as static or transient as per your requirement. The reverse process of serialization is called deserialization in which byte streams are used to create the actual java objects in memory. Serialization offers the following advantages:

  1. Used to save or persist the state of the object
  2. ii) Can be beneficial for objects so that they can travel across the networks easily.

Through serialization, we can only save non-static data members while transient variables are not saved. Object constructors are not called at the time of deserialization. If any parent class has a serializable interface then it is not necessary that child class should implement it but vice-versa is not true in such case.

Serialization through XML

Java serialization feature is used to convert the Java objects into bytes so that they can be sent over the network. Sometimes XML like language may be required so that the objects can suit multiple platforms. XML is a cross-platform medium and the applications can work on different technologies and platforms if they would be sent through XML. In Java, objects are being serialized to an XML file and are then de-serialized back to the Java object or language.

Read: What Is The Solution Of Java Error: Command Not Found?

Following we have given the examples of creating Java classes that will be serialized to XML and then we will again de-serialize them to Java object. Following code shows it:

public class UserClass{
public UserClass(){}
private Integer firstfield;
private String secondfield;
private Booleans thirdfield;
public Integer getFirstField(){return firstfield;}
public void setFirstField(Integer firstfield)

Now we can do serialization through XML Encoder to convert Java object to an XML file. The following code is used for this purpose that will convert the Java objects into XML file:

public String getSecondField(){return secondfield;}
public void setSecondField(String secondfield)
public Boolean isThirdField()
return thirdfield;}
public void setThirdField(boolean thirdfield)
public String toString(){
 return “UserClass Settings are [ firstfield =” + firstfield + “, secondfield =” + secondfield + “,thirdfield=” + thirdfield + “]”;}}
private static void serializateToXML (UserClass userSettings) throws IOException
fileOutputStream fos=new FileOutputStream(“userSettings.xml”);
XMLEncoder encoder = new XMLEncoder(fos);
encoder.setExcepionListener(new ExceptionListener()
public void exceptionThrown(Exception e){
system.out.println(“Exception is :” +e.toString());

Reflection is used by XML Encoder to identify what fields are contained by them. It does not write the fields to binary instead write them to XML. Java objects that are serialized or encoded are supposed to follow the Java Beans Specifications like the listed following:

  1. The object has a no-argument type constructor
  2. For each of the private or protected field, the object must have getter and setter methods

On execution of above-mentioned code, it will generate an XML file with the following structure and code:

Read: Hibernate Interview Questions And Answers
<?xml version=”1.0” encoding=”UTF-8”?>
<java version=”1.8.0_92” class=”java.beans.XMLDecoder”>
    <object class=”com.howtodoinjava.log4j2.examples.UserClass”>
     <void property=”firstfield”>

Here in such case if the default value of the object will not be changed then it will be skipped by the XML Encoder means it will not alter the default value. Like in above example, the third field is of the boolean type with default value false, so it will remain same between all of the class versions.

De-serialization from XML to java object using XML Decoder

XML Decoder is used to convert XML file back to a java object. The below-mentioned code is used for this purpose in Java.

private static UserClass deserializeFromXML() throws IOException
fileInputStream fis = new FileInputStream(“usersettings.xml”);
XMLDecoder decoder = new XMLDecoder(fis);
userClass decodeSettings=(UserClass) decoder.readObject();
return decodeSettings;


Serialization of objects is much more important and beneficial for the Java objects. It increases the speed of data transfer across networks. Java provides serialization and de-serialization concepts through Java packages that can be imported into Java class files to make the objects serializable. In case if the user does not want to make any data object serializable then he or she can easily do so by making that variable transient. A computer can understand only four types of streams that are byte stream, a character stream, data stream and object stream. So, the source must create the objects that can be easily understood by the destination system and that are what is achieved through serialization.

Read: How to Call a Method in Java?

    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Search Posts


Receive Latest Materials and Offers on Java Course