skip to content

System, Base64, UUID, Properties

A few small JDK classes turn up in almost every codebase: System, Base64, UUID and Properties. Interviewers ask them because each has one behaviour that people get wrong.

part ofJavaread it →
on this pageshow

questions

4

What does java.util.Base64 do, how do its basic, URL and MIME encoders differ, and why is Base64 not encryption?

level: juniorimportance: should knowfreq 47%

answer

  1. binary to text and back
  2. 6 bits per character
  3. 3 bytes in, 4 characters out
  4. two alphabet characters, or line breaks
  5. no key means anyone can reverse it

basics

~20 s

java.util.Base64 turns bytes into printable text and back, mapping 3 bytes to 4 characters with = padding at the end. Basic uses + and /, URL uses - and _, MIME adds line breaks. With no key, anyone can decode it.

solid answer

~40 s

`java.util.Base64` provides static factories for encoders and decoders that represent binary data as printable ASCII text. Every 3 input bytes, 24 bits, are split into four 6-bit values, each indexing a 64-character alphabet, so the output is about a third larger; a final group of 1 or 2 bytes is completed with `==` or `=`. `getEncoder()` uses `+` and `/` with no line breaks, `getUrlEncoder()` swaps those for `-` and `_` but still pads unless you call `withoutPadding()`, and `getMimeEncoder()` keeps the basic alphabet and breaks lines at 76 characters with CRLF. The basic and URL decoders reject characters outside the alphabet, while the MIME decoder ignores them. It is not encryption because there is no key: anyone can reverse it with a decoder, so it gives text safety and no confidentiality.

code

java · 17 lines
java
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Demo {
    public static void main(String[] args) {
        byte[] text = "Ma".getBytes(StandardCharsets.UTF_8);
        System.out.println(Base64.getEncoder().encodeToString(text)); // TWE=

        byte[] raw = {(byte) 0xfb, (byte) 0xff};
        System.out.println(Base64.getEncoder().encodeToString(raw));                     // +/8=
        System.out.println(Base64.getUrlEncoder().encodeToString(raw));                  // -_8=
        System.out.println(Base64.getUrlEncoder().withoutPadding().encodeToString(raw)); // -_8

        byte[] back = Base64.getDecoder().decode("TWE=");
        System.out.println(new String(back, StandardCharsets.UTF_8)); // Ma
    }
}

go deeper

for a junior

Recall that Base64 turns bytes into text, that 3 bytes become 4 characters, and that it protects nothing because there is no key. Name the three factory methods.

for a middle

Explain the 6-bit split, how 1 or 2 leftover bytes produce == or =, which alphabet each encoder uses, and that the URL encoder still pads unless withoutPadding is used.

for a senior

Show the judgment: pick strict decoders for untrusted input because the MIME decoder ignores stray characters, stream large payloads with wrap, and budget for the size growth of about a third.

for a principal

Weigh embedding binary data as Base64 in text formats against sending it separately: one self-contained document costs a third more bytes plus encoding work, and reviewers must catch Base64 being passed off as protection.

## What java.util.Base64 does `java.util.Base64`, added in Java 8, converts **binary data to text and back**. Many channels carry text more reliably than raw bytes: a JSON field, a URL, an email body. Base64 rewrites any bytes using a small set of printable ASCII characters so that they survive those channels. The class itself holds only static factories; the work happens in its nested `Base64.Encoder` and `Base64.Decoder`, whose instances are safe to share between threads. It works on bytes, not strings, so text needs a charset step: `s.getBytes(StandardCharsets.UTF_8)` before encoding and `new String(bytes, StandardCharsets.UTF_8)` after decoding. ## How 3 bytes become 4 characters A byte holds 8 bits and a Base64 character carries 6, so the encoder works in groups of 24 bits: 1. Take 3 input bytes, giving 24 bits. 2. Split them into four 6-bit values, each from 0 to 63. 3. Use each value as an index into a 64-character alphabet. 4. Repeat until fewer than 3 bytes remain, then complete the last group with padding. The alphabet is `A` to `Z`, `a` to `z`, `0` to `9` and two more characters, and those two are where the variants differ. The ASCII bytes of `Man` show the split: - bits: `01001101 01100001 01101110` - regrouped in sixes: `010011 010110 000101 101110` - values 19, 22, 5 and 46, which index `T`, `W`, `F` and `u`, giving `TWFu` **Padding** deals with the end of the data, because the output comes in units of four characters. Zero bits fill out the last 6-bit value, and `=` stands in for each missing character: - 2 bytes left: 3 characters plus `=`, so `Ma` becomes `TWE=`. - 1 byte left: 2 characters plus `==`, so `M` becomes `TQ==`. - 0 bytes left: no padding. With padding, the output is `4 * ceil(n / 3)` characters for `n` bytes, about a third larger than the input, which makes Base64 the opposite of compression. ## The three encoders | Variant | Factory | Last two alphabet characters | Line breaks | Its decoder on characters outside the alphabet | |---|---|---|---|---| | Basic | `getEncoder()` | `+` and `/` | None | Rejects them with `IllegalArgumentException` | | URL and filename safe | `getUrlEncoder()` | `-` and `_` | None | Rejects them with `IllegalArgumentException` | | MIME | `getMimeEncoder()` | `+` and `/` | CRLF, at most 76 characters per line, none after the last | Ignores them | The practical consequences: - **The URL encoder still pads.** It only swaps `+` and `/`, which have special meaning in URLs and file paths. Call `withoutPadding()` to drop the `=`. That method returns a new encoder and leaves the original as it was, so discarding the return value changes nothing. - **Padding is optional when decoding.** A decoder accepts a final unit without `=`, but if padding is present it must be the correct amount, otherwise `IllegalArgumentException` follows. - **Decoders are not interchangeable.** `getDecoder()` throws on `-` or `_`. `getMimeDecoder()` skips them and often returns wrong bytes with no error: `-__-` decodes to an empty array. It throws only when what is left is not valid Base64. - **Line format is adjustable.** `getMimeEncoder(lineLength, lineSeparator)` sets both, rounding the length down to a multiple of 4. - **Charsets belong to your data, not to Base64.** `encodeToString` and `decode(String)` use ISO-8859-1 for the Base64 text, which is plain ASCII anyway. The charset that matters is the one that turned your own string into bytes, and the decoding side must use the same one. ## Why encoding is not encryption **Encryption** turns data into something only the holder of a key can read. Base64 has no key and no secret: the alphabet and the algorithm are public, and `Base64.getDecoder().decode(text)` reverses it for anyone. RFC 4648 says it directly: base encoding visually hides information such as passwords "but does not provide any computational confidentiality". It gives no integrity either, since nothing detects a changed character that is still in the alphabet. Base64 often appears next to cryptography without being any: an encrypted or hashed result is binary, and Base64 is how it travels as text. For confidentiality use a cipher from `javax.crypto`, and for stored passwords a slow password-hashing function. ## Working with large data `Encoder.wrap(OutputStream)` and `Decoder.wrap(InputStream)` process a stream without first building the whole result in memory. Close the encoding stream when finished: closing flushes any leftover bytes, and it also closes the underlying stream.

  • Why might output from Java's Base64.getUrlEncoder() still need withoutPadding()?
    `getUrlEncoder()` changes only `+` and `/` to `-` and `_`; it still appends `=`, which is a delimiter in a URL query string. `withoutPadding()` returns a new encoder that omits it, and the original is unaffected, so a discarded return value changes nothing. The decoder still reads the result, because padding is accepted but not required.
  • What happens if URL-safe Base64 text reaches the wrong java.util.Base64 decoder?
    `Base64.getDecoder()` throws `IllegalArgumentException` on `-` or `_`, because the basic decoder rejects characters outside its alphabet. `Base64.getMimeDecoder()` ignores them instead, so the call often succeeds with the wrong bytes: `-__-` decodes to an empty array. It throws only when what remains is not valid Base64, as with `-_8=`, which leaves `8=`. Use the strict decoders unless the input really is line-wrapped MIME.
  • How large does java.util.Base64 output get, and how do you handle a large file?
    With padding, `n` bytes become `4 * ceil(n / 3)` characters, about a third more, and the MIME encoder adds a CRLF between lines: 100 bytes give 136 characters from the basic encoder and 138 from the MIME one. For large input use `Encoder.wrap(OutputStream)`, which encodes as you write. Close the wrapper, since closing flushes leftover bytes and also closes the underlying stream.

  • Base64 protects data, because the output is unreadable at a glance.
  • Base64 compresses data by packing bytes into fewer characters.
  • Java's URL encoder drops the = padding by default.
  • The MIME encoder uses a different alphabet from the basic encoder.
  • Calling withoutPadding() changes that encoder in place.
  • Every java.util.Base64 decoder requires the = padding to be present.

java.util.Base64
Java 1.8

context

open as a page

What does java.lang.System provide, how do getProperty and getenv differ, and which of currentTimeMillis and nanoTime measures elapsed time?

level: juniorimportance: should knowfreq 54%

basics

~20 s

java.lang.System is a static utility class for standard streams, properties, the environment, time and array copying. getProperty reads this JVM's settings; getenv reads the OS process environment. Measure elapsed time with nanoTime, since currentTimeMillis is a wall-clock timestamp.

open as a page

What is java.util.Properties, how do load and getProperty defaults work, why is extending Hashtable awkward, and what replaces it for typed configuration?

level: middleimportance: should knowfreq 37%

basics

~20 s

java.util.Properties holds string key-value pairs loaded from a line-based file, with getProperty falling back to a defaults list. Inheriting from Hashtable exposes put calls accepting non-strings and get calls ignoring defaults. For typed settings, parse into an immutable record at start-up.

open as a page

What is java.util.UUID, how do randomUUID and nameUUIDFromBytes produce their bits, and when is a UUID a poor database key or secret token?

level: seniorimportance: should knowfreq 56%

basics

~20 s

java.util.UUID is an immutable 128-bit identifier. randomUUID fills it from SecureRandom (version 4); nameUUIDFromBytes hashes your bytes with MD5 (version 3). Random keys hurt index locality and take twice a sequence's size, and UUIDs should not serve as secret tokens.

open as a page