Base64 Encoding and Decoding Example in Java

In this short Java programming tutorial I am going to share with you how to take a String value and Base64 encode it. We will then take the Base64 encoded String value and will decode it back into original String.

There are different libraries out there that allow us to use Base64 encoding and decoding and probably the easiest one to use will be from java.util package.

Base64 Encoding Example in Java

To encode a String value into Base64 format import into your Java file java.util.Base64 and then follow the example below:

String stringValue = "Hello world";

// Encode this value into Base6 
String stringValueBase64Encoded = Base64.getEncoder().encodeToString(stringValue.getBytes());
System.out.println(stringValue  + " when Base64 encoded is: " + stringValueBase64Encoded);

Base64 Decoding Example in Java

To decode a Base64 encoded String import into your Java file java.util.Base64 follow the example below:

// Decode Base64 encoded value
byte[] byteValueBase64Decoded = Base64.getDecoder().decode(stringValueBase64Encoded);
String stringValueBase64Decoded = new String(byteValueBase64Decoded);

System.out.println(stringValueBase64Encoded  + " when decoded is: " + stringValueBase64Decoded);

Base64 Encoding and Decoding Complete Example

package com.appsdeveloperblog;

import java.util.Base64;

/**
 *
 * @author skargopolov
 */
public class Base64EncodingDecodingExample {
 public static void main(String[] args)
 {
     String stringValue = "Hello world";
     
     // Encode this value into Base6 
     String stringValueBase64Encoded = Base64.getEncoder().encodeToString(stringValue.getBytes());
     System.out.println(stringValue  + " when Base64 encoded is: " + stringValueBase64Encoded);
     
     // Decode Base64 encoded value
     byte[] byteValueBase64Decoded = Base64.getDecoder().decode(stringValueBase64Encoded);
     String stringValueBase64Decoded = new String(byteValueBase64Decoded);
     
     System.out.println(stringValueBase64Encoded  + " when decoded is: " + stringValueBase64Decoded);
 }
}

I hope this short Java programming tutorial is of some help to you.

And as always I am inviting you to check some of the available Java books and Video courses to see if there will be something that can help you take your Software development skills to a new level.

Lean Java – Books

Learning Java – Video Courses