Encoding and Decoding with Java

Thursday May 13th 2021 by MS Sridhar
Article Image

Encoding involves converting data from one form to another. In this developer tutorial, we look at how to Encode and Decode in Java. Read more.

Encoding is a method we can use to convert data from one form or to another in the hopes of keeping it hidden from those that we do not wish to see it. Decoding is how the information gets changed back to allow the intended person access to read the data. Java supprots this via the java.util.Base64 library. We use this library in the example program below, which utilizes Base64 encoding and decoding.


import java.util.Base64;
import java.io.UnsupportedEncodingException;

public class EncodingDecoding
	public static void main(String[] args)
		EncodingDecoding encodingDecoding = new EncodingDecoding();

	private void proceed()
			String stringToBeEncoded = "Base 64 encoding string";
			String encodingType = "utf-8";

			//Encoding using the Base64 encoder
			String encodedString = 
			System.out.println("Base64 encoded string: " + encodedString);

			//Decoding the Base64 decoder
			byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
			String decodedString = new String (decodedBytes, encodingType);
			System.out.println("Base64 decoded string: " + decodedString);
		} catch(UnsupportedEncodingException usee) {
			System.out.println("Exception:" + usee.getMessage());



$java EncodingDecoding
Base64 encoded string: QmFzZSA2NCBlbmNvZGluZyBzdHJpbmc=
Base64 decoded string: Base 64 encoding string
Mobile Site | Full Site