Lesson · Core Utility Classes
Core utility classes: Objects, Arrays, Math, System
13 min readCore Utility Classes
Four workhorses sit in every Java program: Objects for null-safe logic, Arrays for bulk array work, Math for numeric edges, System for timing and copying. Knowing their corners is the difference between a one-liner and a subtle bug.
Objects: the null-safe standard forms
java.util.Objects is the home of the idioms every equals, hashCode and constructor should use. equals(a, b) is null-safe on both sides; hash(...) composes a correct hashCode from fields; requireNonNull turns a missing argument into an early, clear failure; toString(o, default) collapses the ternary.
requireNonNull with a message is the cheapest validation in Java: the exception points at the cause instead of surfacing later as a mysterious NPE three calls away.
Objects.equals(left, right); // null-safe both sides Objects.hash(name, age); // equals-compatible hashCode Objects.requireNonNull(config, "config"); // fail at the door, with a name Objects.toString(value, "(none)");
Toolbox · four classes, one job each
pick a classMath.round(2.5) / Math.round(-2.5)
3 / -2: half toward +infinity
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
true: negation overflows
Math.toIntExact(3_000_000_000L)
ArithmeticException, not truncation
Math.floorDiv(-7, 2) / floorMod(-7, 3)
-4 / 2: floored
Math.clamp(15, 0, 10)
10: range limiter, Java 21
floorDiv and floorMod are what wrapping arithmetic wants: floorMod(-7, 3) is 2, while % gives -1.
Arrays: the bulk operations
java.util.Arrays is what makes arrays ergonomic: sort, binarySearch, fill, copyOf (with grow and pad semantics), equals and toString for every primitive and object type, plus stream for the bridge into pipelines.
Two traps live here. equals and hashCode on an array use identity unless you call the Arrays versions, so arrays in collections behave surprisingly. And copyOf versus copyOfRange differ in what they do when the target length is longer: copyOf pads, copyOfRange from beyond the end throws.
Arrays.sort(nums); // in place, dual-pivot for primitives int[] grown = Arrays.copyOf(nums, 10); // pads with zeros to length 10 Arrays.equals(a, b); // element-wise: a.equals(b) is identity
Math: the corners that bite
Math is the obvious functions with non-obvious edges. round rounds half up toward positive infinity (2.5 becomes 3, -2.5 becomes -2). abs(Integer.MIN_VALUE) overflows back to itself, because the negative range is one larger than the positive. toIntExact converts with an overflow check instead of silently truncating.
floorDiv and floorMod give floored division and modulus, which is what date math and wrapping arithmetic usually want: floorMod(-7, 3) is 2, while the % operator gives -1. Math.clamp (Java 21) is the range limiter everyone used to hand-roll.
| Call | Result | Edge it handles |
|---|---|---|
| Math.round(2.5) / (-2.5) | 3 / -2 | rounds half toward +infinity |
| Math.abs(Integer.MIN_VALUE) | still MIN_VALUE | negation overflow in two's complement |
| Math.toIntExact(3_000_000_000L) | ArithmeticException | no silent truncation |
| Math.floorDiv(-7, 2) | -4 | floor semantics, not truncation |
| Math.floorMod(-7, 3) | 2 | wrapping modulus, always non-negative for positive divisor |
| Math.clamp(15, 0, 10) | 10 | range limiter, Java 21 |
System: timing, copying, environment
System.nanoTime measures elapsed time; System.currentTimeMillis reads wall time. They are not interchangeable: nanoTime is monotonic (never jumps backward for clock adjustments) and is the only correct base for measuring durations. currentTimeMillis exists for timestamps, and for those Instant is better still.
System.arraycopy is the fast bulk copy under every collection: overlapping copies are handled, types are checked at runtime. System.getenv reads environment variables while System.getProperty reads -D properties; both are configuration inputs and belong at the application edge.
long start = System.nanoTime(); // monotonic: measure with this long now = System.currentTimeMillis(); // wall clock: can jump, use Instant instead System.arraycopy(src, 1, dst, 0, 3); // overlapping-safe bulk copy
Base64 and UUID: the everyday encoders
Base64.getEncoder turns bytes into text for transport (URLs, JSON, headers) and the decoder reverses it, with URL-safe and MIME variants for their respective alphabets. Base64 is encoding, not security: it hides nothing.
UUID.randomUUID gives a version 4 identifier with 122 random bits, safe as a primary key and unsafe only when you mistake randomness for secrecy. UUID.fromString parses, and version() and variant() read the metadata nibbles.
Base64.getEncoder().encodeToString(bytes); // bytes to text UUID.randomUUID(); // v4: 122 random bits uuid.version(); // 4 for randomUUID
One library, four jobs
Objects makes null logic safe, Arrays makes bulk work sayable, Math names its edges in the javadoc, and System provides the timing and copying primitives everything else builds on. Recognizing which one owns the problem is most of the work.
Interview angles
Why use Objects.equals instead of == or a.equals(b)?+
It is null-safe on both sides: no NPE when either reference is null, and it delegates to equals when both exist. The same family covers hash, requireNonNull and toString defaults for consistent class implementations.
What is surprising about array equals and hashCode?+
Arrays inherit Object's identity versions, so two arrays with the same elements are unequal and hash differently. Use Arrays.equals, Arrays.hashCode, or wrap in List.of for collection semantics.
Math.round versus Math.floor versus Math.ceil?+
round rounds half up toward positive infinity and returns a long/int; floor goes toward negative infinity, ceil toward positive infinity, both returning double when given double. For half-even rounding (banker's) use BigDecimal or Math.rint.
Why does Math.abs(Integer.MIN_VALUE) return a negative number?+
Two's complement ints have one more negative value than positive, so the negation of MIN_VALUE overflows back to MIN_VALUE. Handle the edge explicitly or compute in a wider type (long) first.
nanoTime versus currentTimeMillis?+
nanoTime is monotonic and unitless: the correct choice for durations (always compare two readings, never to a date). currentTimeMillis reads wall time that can jump (NTP, manual changes); for timestamps prefer Instant.now().
Is Base64 encryption?+
No. It is a reversible encoding that turns binary into text; anyone can decode it. Use it for transport, and real cryptographic primitives (or TLS) for anything that must stay secret.