Codectionary / Developer documentation / Java

Base64 Binary Encoding

Base64 converts bytes into a transport-friendly text representation. Java provides basic, MIME and URL-safe variants; these encodings do not encrypt data. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

Base64.getEncoder().encodeToString(bytes); Base64.getDecoder().decode(text)

Examples

Base64 Binary Encoding

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.util.Base64;
import java.nio.charset.StandardCharsets;

public class Main {
  public static void main(String[] args) throws Exception {
    byte[] bytes = "Hello".getBytes(StandardCharsets.UTF_8);
    String encoded = Base64.getEncoder().encodeToString(bytes);
    System.out.println(encoded);
    System.out.println(new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8));
  }
}
  1. Expected output: SGVsbG8= Hello
  2. Text first becomes UTF-8 bytes, then Base64. Decoding reverses those two transformations explicitly.

Best practices

  • Choose the URL-safe encoder for URL components when the protocol requires it.
  • Catch IllegalArgumentException for malformed encoded input.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading