1. Introduction

Base64 is a binary-to-text encoding scheme used to represent binary data in an ASCII string format. In a previous guide, we looked at encoding a String using Base64 in Java. In this guide, we will explore the process of decoding a Base64 encoded String back to its original form.

2. Program Steps

1. Define the Base64 encoded String.

2. Convert the encoded String into a byte array.

3. Decode the byte array using the Base64 class provided by Java.

4. Convert the decoded byte array back to the original String.

5. Print the encoded String and the decoded original String.

3. Code Program

import java.util.Base64;

public class Base64Decode {

    public static void main(String[] args) {
        // Step 1: Define the Base64 encoded String
        String encodedString = "SmF2YVByb2dyYW1taW5nIQ==";

        // Step 2: Convert the encoded String into a byte array
        byte[] encodedBytes = encodedString.getBytes();

        // Step 3: Decode the byte array using Base64
        byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);

        // Step 4: Convert the decoded byte array back to the original String
        String originalString = new String(decodedBytes);

        // Step 5: Print the encoded String and the decoded original String
        System.out.println("Encoded String: " + encodedString);
        System.out.println("Original String: " + originalString);
    }
}

Output:

Encoded String: SmF2YVByb2dyYW1taW5nIQ==
Original String: JavaProgramming!

4. Step By Step Explanation

Step 1: We start by defining the Base64 encoded String encodedString.

Step 2: The encoded String is converted to a byte array encodedBytes using the getBytes() method.

Step 3: Java provides a Base64 class that contains a method getDecoder().decode() which is used to decode the byte array encodedBytes.

Step 4: The decoded byte array decodedBytes is then converted back to the original String originalString.

Step 5: Finally, we print out the encoded String and the decoded original String to the console.