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));
}
}- Expected output: SGVsbG8= Hello
- 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