Static methods in interfaces
Code Comparison
// Separate utility class needed
public class ValidatorUtils {
public static boolean isBlank(
String s) {
return s == null ||
s.trim().isEmpty();
}
}
// Usage
if (ValidatorUtils.isBlank(input)) { ... }
public interface Validator {
boolean validate(String s);
static boolean isBlank(String s) {
return s == null ||
s.trim().isEmpty();
}
}
// Usage
if (Validator.isBlank(input)) { ... }
Why the modern way wins
๐ฆ
Better organization
Keep related utilities with the interface, not in a separate class.
๐
Discoverability
Factory and helper methods are found where you'd expect them.
๐งฉ
API cohesion
No need for separate *Utils or *Helper classes.
Old Approach
Utility classes
Modern Approach
Interface static methods
JDK Support
Static methods in interfaces
Available
Available since JDK 8 (March 2014)
How it works
Before Java 8, utility methods related to an interface had to live in a separate class (e.g., Collections for Collection). Static methods in interfaces let you keep related utilities together. Common in modern APIs like Comparator.comparing(), Stream.of(), and List.of().
Related Documentation
Proof