← Back to Chapters

Base64 Encoding & Decoding

? Base64 Encoding & Decoding

? Quick Overview

Base64 is a binary-to-text encoding scheme used to safely transmit binary data (such as images, files, or encrypted bytes) over text-based protocols like HTTP, JSON, and XML. In Advanced Java, Base64 encoding and decoding is commonly handled using the java.util.Base64 class.

? Key Concepts

  • Encodes binary data into ASCII characters
  • Uses characters A–Z, a–z, 0–9, +, / and = (padding)
  • Not encryption — only encoding
  • Widely used in JWT, REST APIs, file uploads, and email

? Syntax & Theory

Java 8 introduced the Base64 utility class which provides encoders and decoders for different use cases.

  • Basic Standard Base64 encoding
  • URL URL-safe encoding
  • MIME MIME-friendly encoding with line breaks

⚡ Interactive Playground

Type in either box to see the real-time conversion (simulated via JS).

Ready

? Code Example — Encoding

? View Code Example
// Encode a string into Base64 format
import java.util.Base64;

public class Base64EncodeExample {
public static void main(String[] args) {
String original = "Advanced Java";
String encoded = Base64.getEncoder().encodeToString(original.getBytes());
System.out.println(encoded);
}
}

? Code Example — Decoding

? View Code Example
// Decode a Base64 encoded string back to original text
import java.util.Base64;

public class Base64DecodeExample {
public static void main(String[] args) {
String encoded = "QWR2YW5jZWQgSmF2YQ==";
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes);
System.out.println(decoded);
}
}

? Live Output / Explanation

Output

The string "Advanced Java" is converted into a Base64 encoded representation. Decoding restores the original readable text without any data loss.

✅ Tips & Best Practices

  • Never use Base64 as a security mechanism
  • Always specify character encoding when converting strings to bytes
  • Use URL-safe encoder for query parameters
  • Avoid unnecessary encoding to reduce payload size

? Try It Yourself

  • Encode and decode user input from console
  • Encode image bytes into Base64 string
  • Use URL encoder and compare output
  • Integrate Base64 in a REST API response