Utility Classes and Static Factory Methods
Design non-instantiable utility classes and expose static factory methods as alternatives to constructors.
Utility Classes and Static Factory Methods is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Utility Classes and Static Factory Methods
Utility classes provide static helper methods with no instance state. Static factory methods are named alternatives to constructors that offer better readability, caching, and flexibility.
Utility Classes
A utility class has no instance state — it is a container of static methods. Make it non-instantiable by declaring a private constructor.
final class StringUtils {
// Private constructor prevents instantiation
private StringUtils() {
throw new UnsupportedOperationException("Utility class");
}
public static boolean isBlank(String s) {
return s == null || s.strip().isEmpty();
}
public static String capitalize(String s) {
if (isBlank(s)) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase();
}
}
System.out.println(StringUtils.isBlank(" ")); // true
System.out.println(StringUtils.capitalize("hELLO")); // HelloStandard Library Utility Classes
Java's standard library is full of utility classes: Collections, Arrays, Objects, Files, Paths, Math.
import java.util.*;
List<Integer> nums = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9, 3));
Collections.sort(nums);
System.out.println(nums); // [1, 2, 3, 5, 8, 9]
System.out.println(Collections.min(nums)); // 1
System.out.println(Collections.max(nums)); // 9
Collections.shuffle(nums); // random order
int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [1, 1, 3, 4, 5]
System.out.println(Arrays.binarySearch(arr, 4)); // 3 (index)Static Factory Methods
A static factory method is a named static method that creates and returns an instance. Benefits: descriptive names, can return cached/subtype instances, can return null.
class Connection {
private final String host;
private final int port;
private final boolean ssl;
private Connection(String host, int port, boolean ssl) {
this.host = host; this.port = port; this.ssl = ssl;
}
// Named factory methods — more expressive than constructors
public static Connection plain(String host) {
return new Connection(host, 80, false);
}
public static Connection secure(String host) {
return new Connection(host, 443, true);
}
}
Connection c = Connection.secure("api.example.com");
// Much clearer than: new Connection("api.example.com", 443, true)Caching with Static Factory
Static factories can return cached instances, avoiding repeated allocation for common values (like Integer.valueOf does for -128..127).
class Color {
private static final Map<String, Color> CACHE = new HashMap<>();
public final int r, g, b;
private Color(int r, int g, int b) {
this.r = r; this.g = g; this.b = b;
}
public static Color of(int r, int g, int b) {
String key = r + "," + g + "," + b;
return CACHE.computeIfAbsent(key, k -> new Color(r, g, b));
}
public static final Color RED = of(255, 0, 0);
public static final Color GREEN = of(0, 255, 0);
public static final Color BLUE = of(0, 0, 255);
}
System.out.println(Color.of(255,0,0) == Color.RED); // true (cached)Factory vs Constructor: Naming
Common naming conventions for static factory methods:
of— aggregate factoryfrom— converting factoryvalueOf— converting factory (older APIs)getInstance— singletoncreate/newInstance— fresh objectget— flexible
// Java API examples:
Optional.of(value) // of
LocalDate.from(temporal) // from
Integer.valueOf(42) // valueOf
Calendar.getInstance() // getInstance
Array.newInstance(type, length) // newInstance
// Your own:
HttpRequest.post("https://api.example.com/users")
ApiResponse.error(404, "Not found")
Payment.creditCard("4242...", 9999, "USD")Returning Subtypes
A factory method can return a subtype while the declared return type is the interface. Callers are decoupled from the concrete implementation.
interface Validator<T> {
boolean validate(T value);
String errorMessage();
}
class EmailValidator implements Validator<String> {
public boolean validate(String email) { return email.contains("@"); }
public String errorMessage() { return "Invalid email address"; }
}
class Validators {
// Returns interface type — hides implementation
public static Validator<String> email() { return new EmailValidator(); }
public static Validator<String> notBlank() {
return new Validator<>() {
public boolean validate(String s) { return s != null && !s.isBlank(); }
public String errorMessage() { return "Value required"; }
};
}
}Builder via Static Factory
Combine a private constructor with a static factory and a nested Builder for complex object construction.
class EmailMessage {
private final String to, subject, body;
private final boolean html;
private EmailMessage(Builder b) {
this.to = b.to; this.subject = b.subject;
this.body = b.body; this.html = b.html;
}
public static Builder builder(String to) { return new Builder(to); }
public static class Builder {
private final String to;
private String subject = "", body = "";
private boolean html = false;
Builder(String to) { this.to = to; }
public Builder subject(String s) { this.subject = s; return this; }
public Builder body(String b) { this.body = b; return this; }
public Builder html() { this.html = true; return this; }
public EmailMessage build() { return new EmailMessage(this); }
}
}
EmailMessage.builder("alice@co.com").subject("Welcome!").html().build();Validation in Factory Methods
Factory methods are great for input validation before construction — throw meaningful exceptions with context.
class PortNumber {
private final int value;
private PortNumber(int value) { this.value = value; }
public static PortNumber of(int port) {
if (port < 1 || port > 65535)
throw new IllegalArgumentException(
"Port must be 1-65535, got: " + port);
return new PortNumber(port);
}
public static PortNumber http() { return new PortNumber(80); }
public static PortNumber https() { return new PortNumber(443); }
public int value() { return value; }
public boolean isPrivileged() { return value < 1024; }
}
System.out.println(PortNumber.https().isPrivileged()); // trueCollections API: Static Factories
Java 9+ added List.of(), Set.of(), Map.of() — static factory methods that create immutable collections.
import java.util.*;
List<String> fruits = List.of("Apple", "Banana", "Cherry");
Set<Integer> ids = Set.of(1, 2, 3, 4, 5);
Map<String, Integer> ages = Map.of("Alice", 30, "Bob", 25);
// All are unmodifiable:
try {
fruits.add("Durian"); // UnsupportedOperationException
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify!");
}
// Map.entry and Map.ofEntries for > 10 entries
Map<String, String> config = Map.ofEntries(
Map.entry("host", "localhost"),
Map.entry("port", "8080")
);When to Prefer Factory Methods
Prefer static factory methods over constructors when:
- You want a descriptive name
- The factory may return a cached or subtype instance
- Validation before construction is needed
- You want to control the number of instances (Singleton, pool)
// Constructor: hard to know what this means
new Complex(0.5, -1.2);
// Factory: clear meaning
Complex.fromPolar(1.3, Math.PI / 4); // polar form
Complex.rectangular(0.5, -1.2); // rectangular form
// Constructor: no caching
new Boolean(true); // deprecated — creates new object!
// Factory: returns cached instance (Boolean.TRUE or FALSE)
Boolean.valueOf(true); // returns Boolean.TRUE singletonQuick Check
What is the main advantage of a static factory method over a public constructor?
Recap: Utility Classes and Static Factory Methods
Key takeaways:
- Utility classes: final class with private constructor and all-static methods
- Static factory methods are named alternatives to constructors
- Common naming: of, from, valueOf, getInstance, create, newInstance
- Factories can return cached instances — see Integer.valueOf(-128..127)
- Factories can return subtypes while hiding the concrete implementation
- Use builders within factories for complex multi-parameter construction
Frequently asked questions
Is the “Utility Classes and Static Factory Methods” lesson free?
Yes — the full text of “Utility Classes and Static Factory Methods” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Utility Classes and Static Factory Methods”?
Design non-instantiable utility classes and expose static factory methods as alternatives to constructors. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Utility Classes and Static Factory Methods” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Method Overloading Rules
- Varargs Parameters
- Static Fields and Constants
- Utility Classes and Static Factory Methods