Today's Offer - Java Certification Training - Enroll at Flat 10% Off.

- 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: Java Interview Questions and Answers for Experienced, Fresher Developer

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 Difference Between Java And JavaScript?

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:


this.firstfield=firstfield;
public String getSecondField(){return secondfield;}
public void setSecondField(String secondfield)
public Boolean isThirdField()
{
return thirdfield;}
public void setThirdField(boolean thirdfield)
{this.thirdfield=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());
})
encoder.writeObject(settings);
encoder.close();
fos.close();}
}

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: How Long Does It Take To Learn Java?

<?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”>
            <int>10000</int>
    </void>
</object>
</java> 

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();
decoder.close();
fis.close();
return decodeSettings;
} 

Conclusion

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: Frequently Asked J2EE Interview Questions and Answers You Must Read

    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.


Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

2 days 24 Nov 2019

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

3 days 25 Nov 2019

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

3 days 25 Nov 2019

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

4 days 26 Nov 2019

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

12 days 04 Dec 2019

Course for testing

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

32 days 24 Dec 2019

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

11 days 03 Dec 2019

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

3 days 25 Nov 2019

SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

0 day 22 Nov 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews