Base64 Encoding Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Base64 Encoding runs in O(n) time and O(n) space, in Java as in every other language.
- ✓`java.util.Base64`, a factory of immutable codecs: `Base64.getEncoder()`, `getUrlEncoder()`, `getMimeEncoder()` and their `getDecoder()` counterparts.
- ✓Codecs are immutable and thread-safe, so a reviewer expects `private static final Base64.Encoder` fields rather than a `getUrlEncoder().withoutPadding()` call inside a loop.
- ✓The Java trap: The three decoders disagree about whitespace and nobody documents that at the call site. `Base64.getDecoder()` throws `IllegalArgumentException` on ANY character outside its alphabet -- including the CRLF line breaks in a PEM certificate or a MIME body -- while `getMimeDecoder()` skips them silently.
- ✓HotSpot intrinsifies the base64 encode and decode inner loops to vector instructions on x86-64, so throughput after JIT warm-up is far above what the bytecode suggests -- but the first few thousand calls run interpreted, which is why microbenchmarks without a warm-up phase report nonsense.
What Base64 Encoding actually is
Base64 Encoding in Java: what you actually reach for
Java implementation
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
public final class Base64Demo {
// encoders are immutable and thread-safe: build once, share everywhere
private static final Base64.Encoder URL = Base64.getUrlEncoder().withoutPadding();
public static void main(String[] args) {
byte[] data = "Hello, \uD83D\uDC4B".getBytes(StandardCharsets.UTF_8);
String token = URL.encodeToString(data);
byte[] back = Base64.getUrlDecoder().decode(token);
System.out.println(token + " " + new String(back, StandardCharsets.UTF_8));
byte[] big = "Hello, \uD83D\uDC4B ".repeat(20).getBytes(StandardCharsets.UTF_8);
String mime = Base64.getMimeEncoder().encodeToString(big); // CRLF every 76 cols
// Base64.getDecoder().decode(mime) throws IllegalArgumentException on that CRLF
System.out.println(Arrays.equals(Base64.getMimeDecoder().decode(mime), big));
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Base64 Encoding?
`java.util.Base64`, a factory of immutable codecs: `Base64.getEncoder()`, `getUrlEncoder()`, `getMimeEncoder()` and their `getDecoder()` counterparts. `Base64.Encoder.encodeToString(byte[])` returns a String, `encode(byte[])` returns `byte[]`, and `withoutPadding()` returns a new encoder with '=' suppressed. There are wrap/stream forms too: `encoder.wrap(OutputStream)` and `decoder.wrap(InputStream)`. The legacy routes are dead ends: `sun.misc.BASE64Encoder` was internal and removed, and `javax.xml.bind.DatatypeConverter` left the JDK with JAXB.
What is the most common Java mistake when implementing Base64 Encoding?
The three decoders disagree about whitespace and nobody documents that at the call site. `Base64.getDecoder()` throws `IllegalArgumentException` on ANY character outside its alphabet -- including the CRLF line breaks in a PEM certificate or a MIME body -- while `getMimeDecoder()` skips them silently. Code that reads a `.pem` file and calls `getDecoder().decode(...)` works on a hand-pasted one-line test fixture and explodes on every real file. The URL decoder is equally strict in the other direction: it rejects '+' and '/', so standard-alphabet input fails there too.
How does Base64 Encoding actually perform in Java?
HotSpot intrinsifies the base64 encode and decode inner loops to vector instructions on x86-64, so throughput after JIT warm-up is far above what the bytecode suggests -- but the first few thousand calls run interpreted, which is why microbenchmarks without a warm-up phase report nonsense. `encodeToString` allocates a `byte[]` and then a `String`; on a JVM with compact strings the ASCII result stays one byte per char, so the string is 4/3 of the input rather than 8/3. Reuse `wrap(OutputStream)` for large payloads to avoid materialising both. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.