Whenever there are portions of code that are duplicated and do not depend on the state of their container class, they can be centralized inside a "utility class". A utility class is a class that only has static members, hence it should not be instantiated.
When a class contains public static void main(String[] args) method it is not considered as a utility class and will be ignored by
this rule.
To prevent the class from being instantiated, you should define a non-public constructor. This will prevent the compiler from implicitly generating a public parameterless constructor.
class StringUtils { // Noncompliant
public static String concatenate(String s1, String s2) {
return s1 + s2;
}
}
class StringUtils { // Compliant
private StringUtils() {
throw new IllegalStateException("Utility class");
}
public static String concatenate(String s1, String s2) {
return s1 + s2;
}
}