DevToolsForYou

Base64 Encoder and Decoder in Java — Code Examples

Base64 Encoder and Decoder in JavaUse the online tool →

Base64 encoding converts binary or text data into a 64-character ASCII alphabet so it can be safely transmitted over text-only channels. Here is how to encode and decode Base64 in each language using only the standard library.

Java 8+ includes java.util.Base64. Use getEncoder() for standard Base64 and getUrlEncoder() for URL-safe encoding.

Java 8+
import java.util.Base64;
import java.nio.charset.StandardCharsets;

public class Base64Example {
    public static void main(String[] args) {
        String input = "Hello, world!";

        // Encode
        String encoded = Base64.getEncoder()
            .encodeToString(input.getBytes(StandardCharsets.UTF_8));
        System.out.println(encoded); // SGVsbG8sIHdvcmxkIQ==

        // Decode
        byte[] decodedBytes = Base64.getDecoder()
            .decode("SGVsbG8sIHdvcmxkIQ==");
        String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
        System.out.println(decoded); // Hello, world!

        // URL-safe (no + or /, with padding)
        String urlEncoded = Base64.getUrlEncoder()
            .encodeToString(input.getBytes(StandardCharsets.UTF_8));

        // URL-safe without padding
        String noPadding = Base64.getUrlEncoder().withoutPadding()
            .encodeToString(input.getBytes(StandardCharsets.UTF_8));
    }
}
Notes & gotchas
  • Always specify StandardCharsets.UTF_8 explicitly to avoid platform encoding surprises.
  • Use getUrlEncoder() for JWT payloads and URL query parameters.
  • getUrlEncoder().withoutPadding() matches the JWT specification.
Try it in your browser

Need to base64 encode/decode without writing code? The Base64 Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open Base64 Encode/Decode
Base64 Encoder and Decoder in other languages