Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Base64


How to encode and decode a message in Java using Base64 encoding? Since Java 8 there is Base64 class for encoding and decoding bytes. Here we show how to use it.


In Java 8 not only language features have been added, but also a lot of new classes. One of them is java.util.Base64 that allows to encode and decode bytes using Base 64 encoding, which is a standard for encoding email attachments.

In the following example we’ll show how to encode and decode arrays of bytes using Encoder and Decoder from Base64 class:


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

public class Base64Encoder {

    public static void main(String[] args) {
        String message = "Hello, world!\nAnkaŭ en alia lingvo!";
        System.out.println("Original: " + message);

        byte[] bytesToEncode = message.getBytes(StandardCharsets.UTF_8);

        byte[] encoded = encode(bytesToEncode);


    private static byte[] encode(byte[] bytesToEncode) {
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] encoded = encoder.encode(bytesToEncode);
        System.out.println("Encoded: " + new String(encoded));
        return encoded;

    private static void decode(byte[] encoded) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decoded = decoder.decode(encoded);
        System.out.println("Decoded: " + new String(decoded));

Quite easy, no? :-) And here’s the output of running the above example:

Original: Hello, world!
Ankaŭ en alia lingvo!
Encoded: SGVsbG8sIHdvcmxkIQpBbmthxa0gZW4gYWxpYSBsaW5ndm8h
Decoded: Hello, world!
Ankaŭ en alia lingvo!

As you can see the message has been nicely converted to Base64 and back to string. Finally, thanks to Java 8, no need to use external libraries for this common task.

Share with the World!