Why am I getting this warning about utility classes in Java

It means that someone can write:

HelloWorld helloWorld = new HelloWorld();

when you probably don't want them to - you're not providing any instance members, so why allow them to create instances? Rewrite your code as:

final class HelloWorld {

    private HelloWorld() {
        // Prevent instantiation
        // Optional: throw an exception e.g. AssertionError
        // if this ever *is* called
    }

    public static void main(String[] args) {
        System.out.println("Hola Mundo!");
    }
}

What Jon said, but you should know too that every class has a constructor, whether you declare one or not. If you do not declare one, then the "default constructor" is implicitly defined for you.

In other words, these two classes are identical in behaviour:

public class ClassA {
}


public class ClassB {
    public ClassB() {
    }
}

BEWARE: Having a private constructor does not prevent instantiation!

And just to be anal, having a private constructor does not prevent someone from instantiating your class, it just makes it harder:

There are (at least) two ways to get around it:

Declare a factory method (obvious, but if it's your company's code, someone can do this):

public class ClassA {
    private ClassA() {}

    public static ClassA create() {
        return new ClassA(); // oops! this one got away
    }
}

Use reflection (sneaky, and seems wrong somehow, but it works!):
public class ClassA {
    private ClassA() {}
}

// Elsewhere, in another class across town:
Constructor<?> constructor = ClassA.class.getDeclaredConstructor();
// constructor private? no problem... just make it not private!
constructor.setAccessible(true); // muhahahaha
Object obj = constructor.newInstance();
System.out.println(obj.getClass().getSimpleName());  // Prints ClassA!

The only way to guarantee no one creates an instance is to throw an exception in a (might as well make it private) constructor:

public class ClassA {
    private ClassA() {
        throw new UnsupportedOperationException();
    }
}

Tags:

Java