Black Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook  - SCHEDULE CALL

- 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: A Complete Guide to Advanced Java Programming

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: Java String Functions & Methods with Examples

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: 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”>
            <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: Java Programmer Resume Template Sample - Guide for Fresher & Experienced


fbicons FaceBook twitterTwitter lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

-1 day 23 Nov 2024

QA Course

QA

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

Upcoming Class

-1 day 23 Nov 2024

Salesforce Course

Salesforce

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

Upcoming Class

-1 day 23 Nov 2024

Business Analyst Course

Business Analyst

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

Upcoming Class

-1 day 23 Nov 2024

MS SQL Server Course

MS SQL Server

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

Upcoming Class

-1 day 23 Nov 2024

Data Science Course

Data Science

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

Upcoming Class

-1 day 23 Nov 2024

DevOps Course

DevOps

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

Upcoming Class

3 days 27 Nov 2024

Hadoop Course

Hadoop

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

Upcoming Class

12 days 06 Dec 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

6 days 30 Nov 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

-1 day 23 Nov 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

33 days 27 Dec 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

12 days 06 Dec 2024

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews