Encoding/Decoding In Java

Encoding/Decoding is the method of representing an data, to a different format so that data can be transferred through the network or web.

Encoder usually converts the data into web representation and after received in the other end, decoder converts back the web representation data to original data.

1. Base64 Encoding/Decoding

Base64 is a way of handling binary/any characters to text format so that the information can be easily transmitted via network between systems.

Below is the sample Base64 encode decode, present in Java.


2. XML Encoding/Decoding

A more commonly widely used interchange format is XML., and we can convert Java Objects to XML, save with state, and also pass it to external systems, and decode the XML back to Java Objects.

java.beans.* package provides XMLEncoder and XMLDecoder by default for XML encoding/decoding.

Below example shows how a Java Object is converted to XML and XML is converted back to Java Object.

However the Java Object or Pojo (in this case Ticket class) which needs to be encoded to XML needs to be public class.

In the below example, a movieTicket object of Ticket class is created and it is converted to XML using XMLEncoder class, and when the XML is printed, we could the corresponding values are also printed.(state is maintained)

Again, when the XML with state is decoded using XMLDecoder class, we could see the Object created back with the same state..(with showName, showTiming & price)

Leave a Reply

Your email address will not be published. Required fields are marked *