This is a base64 tutorial and example in Java. You will learn how to encode and decode data using this scheme.

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Example – How to Encode and Decode a string using Base64 scheme

This example demonstrates how to programmatically encode and decode a piece of string in java.

Step 1: Add imports

Add the following imports in your java file:

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

Create the class and define the main method, throwing an UnsupportedEncodingException in case such an error is raised:

 public class Base64JavaExample {
    public static void main(String[] args) throws UnsupportedEncodingException {

Now obtain the encoder from the Base64 class and invoke the encodeToString() method:

         String base64Encoding=Base64.getEncoder().encodeToString("HelloWorld".getBytes("utf-8"));

Then to decode, you obtain the decoder and decode method, passing in the encoded string:

         byte[] base64Decoding=Base64.getDecoder().decode(base64Encoding);

Full Code

Here’s the full code:

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

/**
 * Base 64 Encoding and Decoding
 *
 */
public class Base64JavaExample {

    public static void main(String[] args) throws UnsupportedEncodingException {

        String base64Encoding=Base64.getEncoder().encodeToString("HelloWorld".getBytes("utf-8"));
        System.out.println("Encoded String is"+base64Encoding);
        byte[] base64Decoding=Base64.getDecoder().decode(base64Encoding);
        System.out.println("Decoded String is "+new String(base64Decoding,"utf-8"));
    }

}

Step 4: Run

Run the code:

$javac Base64JavaExample.java

Here’s what you will get:

Encoded String isSGVsbG9Xb3JsZA==
Decoded String is HelloWorld

Good day!

Categorized in: