Java
Base64 Encoding
Programming
Data Encoding
Software Development

Encoding as Base64 in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Base64 encoding is a method used to convert binary data into a textual representation, primarily for the safe transport of data across systems and networks that might otherwise corrupt the original binary data. In Java, Base64 encoding and decoding can be performed using the java.util.Base64 utility class introduced in Java 8. This class provides a much simpler way to handle Base64 encoding without resorting to external libraries as required in earlier Java versions.

Understanding Base64 Encoding

Base64 encoding schemes are commonly used when there is a need to encode binary data, especially when that data needs to be stored and transferred over media that are designed to deal with textual data. This encoding helps to ensure that the data remains intact without modification during transport. Base64 is based on a 64-character alphabet and operates on 24-bit blocks of data. These 24 bits are split into four segments of 6 bits each, with each segment being converted to one of 64 possible characters.

Java's Base64 Utility Class

Java provides the java.util.Base64 utility class that supports three kinds of Base64 as per RFC 4648:

  • Basic: Uses "A-Za-z0-9+/" as the character set, with "=" as padding.
  • URL and Filename safe: Uses "A-Za-z0-9-_" as the character set, with "=" as padding.
  • MIME: Intended for MIME content, with a max line length of 76 characters and uses "\r\n" as line separator.

These different types ensure that the data can be encoded in a way that is most suitable for its intended use.

How to Use Java Base64

Encoding and Decoding

Here is a simple example showing how to encode and decode strings using Base64 in Java:

java
1import java.util.Base64;
2
3public class Base64Example {
4    public static void main(String[] args) {
5        String originalInput = "Base64 encoding in Java";
6        String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
7
8        System.out.println("Encoded string: " + encodedString);
9
10        byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
11        String decodedString = new String(decodedBytes);
12
13        System.out.println("Decoded string: " + decodedString);
14    }
15}

This program will output:

 
Encoded string: QmFzZTY0IGVuY29kaW5nIGluIEphdmE=
Decoded string: Base64 encoding in Java

Working with Files

For encoding and decoding streams of data, such as files, Java provides Encoder and Decoder classes equipped with methods like wrap(InputStream) for encoding and wrap(OutputStream) for decoding. This allows for efficient encoding and decoding of large files without loading them completely into memory.

Practical Applications

Base64 is widely used in many applications including:

  • Embedding image data in HTML or CSS files.
  • Encoding user credentials in HTTP authentication.
  • Storing complex data in XML or JSON.

Summary

In Java, the java.util.Base64 utility class provides a robust and flexible way to work with Base64 encoding and decoding. Below is a table summarizing the key points mentioned about the functionalities provided by the class:

FunctionalityDescriptionExample Method
Basic EncodingStandard Base64 encodingBase64.getEncoder()
URL Safe EncodingFor use in URLs and filenamesBase64.getUrlEncoder()
MIME EncodingFor MIME friendly outputBase64.getMimeEncoder()
Stream EncodingWrap around streams for large dataEncoder.wrap(InputStream)
Stream DecodingWrap around streams for large dataDecoder.wrap(OutputStream)

Java’s Base64 API is not only easy to use but also eliminates the need for additional third-party libraries, making it a superior choice for any Java developer needing to encode or decode data reliably.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.