{"record":{"id":"291a31cb67353595","repo":"TheAlgorithms/Java","slug":"this-is-a-utility-class-and-cannot-be-instantiated","errorCode":null,"errorMessage":"This is a utility class and cannot be instantiated.","messagePattern":"This is a utility class and cannot be instantiated\\.","errorType":"validation","errorClass":"UnsupportedOperationException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/maths/Average.java","lineNumber":19,"sourceCode":"package com.thealgorithms.maths;\n\nimport java.util.Arrays;\nimport java.util.OptionalDouble;\n\n/**\n * A utility class for computing the average of numeric arrays.\n *\n * <p>This class provides static methods to calculate the arithmetic mean\n * of arrays of both {@code double} and {@code int} values. It also offers\n * a Stream-based alternative for modern, declarative usage.\n *\n * <p>All methods guard against {@code null} or empty inputs.\n */\npublic final class Average {\n\n    // Prevent instantiation of this utility class\n    private Average() {\n        throw new UnsupportedOperationException(\"This is a utility class and cannot be instantiated.\");\n    }\n\n    /**\n     * Computes the arithmetic mean of a {@code double} array.\n     *\n     * <p>The average is calculated as the sum of all elements divided\n     * by the number of elements: {@code avg = Σ(numbers[i]) / n}.\n     *\n     * @param numbers a non-null, non-empty array of {@code double} values\n     * @return the arithmetic mean of the given numbers\n     * @throws IllegalArgumentException if {@code numbers} is {@code null} or empty\n     */\n    public static double average(double[] numbers) {\n        if (numbers == null || numbers.length == 0) {\n            throw new IllegalArgumentException(\"Numbers array cannot be empty or null\");\n        }\n        double sum = 0;\n        for (double number : numbers) {","sourceCodeStart":1,"sourceCodeEnd":37,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/Average.java#L1-L37","documentation":"Thrown by the private constructor of the Average utility class when an attempt is made to instantiate it. Average is a final class containing only static methods; the constructor deliberately throws UnsupportedOperationException to enforce the utility-class pattern. The JVM prevents external instantiation via the private modifier, but reflection or an internal subclass (not possible since the class is final) could theoretically trigger this.","triggerScenarios":"Attempting to instantiate Average via reflection: Average.class.getDeclaredConstructor().setAccessible(true).newInstance(). Calling new Average() directly fails at compile time due to the private constructor, so this only manifests at runtime through reflection.","commonSituations":"A reflection-based framework (dependency injection, serialization library, ORM) that auto-discovers and instantiates classes by scanning packages or annotations. A test utility that tries to instantiate all classes in a package for coverage analysis. A generic factory that reflectively creates instances of any class it encounters.","solutions":["Do not instantiate Average — call its static methods directly (Average.average(arr), Average.averageStream(arr)).","If a reflection framework is auto-instantiating, exclude utility classes or annotate them to be skipped.","If scanning code is the culprit, filter out classes with only static methods or private constructors before attempting instantiation."],"exampleFix":"// before (reflection triggers the exception)\nAverage avg = Average.class.getDeclaredConstructor().setAccessible(true).newInstance();\n\n// after (use static methods — never instantiate)\ndouble mean = Average.average(new double[]{1.0, 2.0, 3.0});","handlingStrategy":"type-guard","validationCode":"// Never instantiate Average — use static methods directly\ndouble mean = Average.average(new double[]{1.0, 2.0, 3.0});\n// If using a reflection framework, skip classes with private constructors:\nif (clazz == Average.class) continue; // skip utility class","typeGuard":"// Check whether a class should be instantiated (utility-class guard)\nstatic boolean isInstantiable(Class<?> clazz) {\n    try {\n        Constructor<?> c = clazz.getDeclaredConstructor();\n        return java.lang.reflect.Modifier.isPublic(c.getModifiers());\n    } catch (NoSuchMethodException e) {\n        return false;\n    }\n}","tryCatchPattern":"// If reflectively scanning packages, catch and skip utility classes\ntry {\n    Object instance = clazz.getDeclaredConstructor().newInstance();\n} catch (UnsupportedOperationException e) {\n    // Skip utility classes that refuse instantiation\n    continue;\n}","preventionTips":["Always call Average methods statically — never use reflection to instantiate utility classes.","If a DI or scanning framework auto-instantiates classes, exclude or annotate utility classes.","Add a filter for classes with private constructors or no public constructor before reflection-based instantiation."],"tags":["utility-class","reflection","instantiation","java","design-pattern"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}