Sub topic 8
Utility classes and private constructors
This chapter assumes you know how to declare static methods and call them through the class name. It also assumes you know what a constructor is and how private and final work. Earlier chapters covered the rules for static context. This chapter looks at one design built from those rules: a class that exists only to hold static methods.
What a utility class is
A utility class is a class that groups related static methods and has no per-object state. You never create an object of it. You call its methods through the class name.
The JDK has many examples:
java.lang.Mathholds numeric functions such asmaxandsqrt.java.util.Arraysholds array helpers such assortandtoString.java.util.Collectionsholds helpers for collections.java.util.Objectsholds null-safe helpers such asrequireNonNull.
Each one is stateless. A call such as Math.max(3, 7) depends only on its arguments, so no object has to exist first.
The problem with the default constructor
If a class declares no constructor, the compiler adds a public no-argument one. A class of only static methods then looks like this:
public class Strings {
public static boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
}Nothing stops a caller from writing new Strings(). It compiles and produces a useless object. Someone can also write class MyStrings extends Strings. That implies an inheritance relationship that means nothing here, because static methods are not overridden (see the chapter on hiding).
The convention fixes both problems with two changes:
- Declare the class
final, so it cannot be subclassed. - Declare a
privateconstructor, so no code outside the class can create an instance.
public final class StringUtils {
private StringUtils() {
throw new AssertionError("No instances");
}
public static boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
}Once you declare any constructor, the compiler stops generating the default one. A private constructor therefore removes the public one.
Why the constructor throws
The spine's basic version uses an empty constructor body. That is enough to block outside callers. Throwing AssertionError adds two protections:
- Code inside the class itself cannot call
new StringUtils()by mistake. Without the throw, it compiles and runs. - Reflection can bypass
privateby callingsetAccessible(true). A throwing constructor makes that attempt fail.
This program shows the reflection case. It must be in the same package as StringUtils:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
Constructor<StringUtils> c = StringUtils.class.getDeclaredConstructor();
c.setAccessible(true);
try {
c.newInstance();
} catch (InvocationTargetException e) {
System.out.println(e.getCause());
}
}
}It prints java.lang.AssertionError: No instances. Reflection wraps the exception thrown by the constructor in an InvocationTargetException. The original error is available through getCause().
An AssertionError is an Error, not an Exception. That fits here, because reaching this constructor means a programming mistake, not a condition a caller should handle.
Why `final` still matters
Some developers write abstract class Helpers instead of final. That blocks new Helpers() but leaves the class open to subclassing. A subclass with an implicit constructor would then call Helpers(), which is fine for an abstract class. With a private constructor, a subclass cannot compile anyway, because it cannot call the superclass constructor. So the private constructor already blocks subclassing, except for nested classes in the same file. Adding final states the intent in the declaration. Tools and readers see it at once, without working out the rule.
| Declaration | `new X()` outside | Subclass outside | Intent clear? |
|---|---|---|---|
| No constructor, not final | Allowed | Allowed | No |
| `abstract` class, no constructor | Blocked | Allowed | Partly |
| Private constructor only | Blocked | Blocked | Mostly |
| `final` plus private constructor | Blocked | Blocked | Yes |
A complete example
This utility class has two methods. One calls the other, and both are stateless.
public final class TextUtils {
private TextUtils() {
throw new AssertionError("No instances");
}
public static boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
public static String capitalize(String s) {
if (isBlank(s)) {
return s;
}
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static void main(String[] args) {
System.out.println(capitalize("java"));
System.out.println(capitalize(" "));
System.out.println(capitalize(null));
}
}The output is Java, then a line with two spaces, then null. Note that capitalize calls isBlank without a class prefix. Inside the same class, a static method can be called by its simple name.
The null behavior is part of the method's contract. Objects.requireNonNull throws on null. isBlank here accepts null and answers true. Choose one behavior for each method and document it. Callers rely on these small details.
Passing in dependencies instead of reaching for them
A utility method is easy to test when its result depends only on its arguments. It becomes hard to test when it reads hidden state, such as the clock. Compare these two:
import java.time.Instant;
public final class Expiry {
private Expiry() {
throw new AssertionError("No instances");
}
// Hard to test: the result depends on the real time
public static boolean isExpiredNow(Instant expiry) {
return Instant.now().isAfter(expiry);
}
// Easy to test: the caller supplies the time
public static boolean isExpired(Instant expiry, Instant now) {
return now.isAfter(expiry);
}
public static void main(String[] args) {
Instant expiry = Instant.parse("2026-01-01T00:00:00Z");
System.out.println(isExpired(expiry, Instant.parse("2025-12-31T23:59:59Z")));
System.out.println(isExpired(expiry, Instant.parse("2026-01-01T00:00:01Z")));
}
}This prints false, then true. A test can pass any time it likes. The first method needs the real clock and can give different answers on different runs. The same idea applies to random numbers, files, and environment variables.
Where utility classes fit
Not every group of helper methods needs its own class. This decision flow summarizes the choice.
The common good cases for a utility class are:
- Operations on types you cannot modify, such as
String,List, orInstant. - Pure functions with no natural owner, such as math helpers.
- Small groups of constants and helpers for one concern, such as a file name parser.
An operation that mostly reads one of your own classes usually belongs on that class. Putting OrderUtils.total(order) outside Order gives up encapsulation. It also splits behavior from the data it uses.
Since Java 8, an interface can hold static methods. List.of and Comparator.comparing use this. For a helper tied to one interface, a static method on the interface itself keeps it discoverable. It also avoids a separate Collections-style companion class. Such an interface cannot be instantiated, so it needs no private constructor.
Common mistakes
- Forgetting the private constructor. The class works, but callers can create meaningless instances. Static analysis tools usually flag this.
- Adding mutable static fields. A utility class should be stateless. A static
Listcache or counter inside it brings in the thread-safety and testing problems covered in later chapters. Constants are fine. Changing state is not. - Creating a catch-all
Utilsclass. A class namedUtilswith unrelated methods grows without limit. Name classes by concern, such asDateFormatsorFileNames, so each stays small. - Making methods depend on hidden state. Static methods that read system properties, the clock, or global singletons cannot be tested in isolation. Pass those values as arguments.
- Using a utility class to avoid objects. Several static methods that all take the same first argument often describe a missing type. Consider whether that argument should be an object with instance methods.
- Expecting to mock static calls. Standard mocking tools replace instance methods easily. Static methods need special tooling, so code that calls
Utils.fetch()directly is harder to replace in tests.
Summary of the pattern
- Make the class
final. - Add a
privateconstructor, and make it throwAssertionError. - Declare every method
static. - Keep the class stateless. Constants are the only static fields.
- Pass in any outside data the methods need.
Static imports, covered in the next chapter, let callers use these methods without the class prefix.
Exercise
A teammate writes public abstract class DateHelpers containing only static methods and no constructor. Name two problems and give the fix.
Show answer
First, the class is not final, so anyone can write class MyHelpers extends DateHelpers, which implies inheritance where there is none. Second, the compiler still generates a public default constructor, so subclasses can create instances, and the intent is unclear. The fix is to declare the class public final class DateHelpers, add a private constructor that throws AssertionError, and keep all methods static.
Exercise
A utility method static boolean isWeekend() calls LocalDate.now() internally. Why is it hard to test, and how do you change the signature?
Show answer
Its result depends on the real current date, so a test cannot control the input and the answer changes from day to day. Change it to static boolean isWeekend(LocalDate date) so the caller supplies the date. A test can then pass a fixed Saturday and a fixed Monday and check the results.