1. Overview

In this tutorial, we’ll explore the difference between Java helper and utility classes. We’ll first examine what each of these means and how to create them.

2. Java Helper Classes

A helper class provides functionalities necessary for the overall running of a Java program. Helper classes contain methods used by other classes to perform repetitive tasks, which aren’t the core purpose of an application.

As the name suggests, they help other classes by providing some functionalities that complement the services provided by those classes.

They contain methods for implementing mundane and repetitive tasks, making the overall code base modular and reusable across multiple classes.

A helper class can be instantiated and may contain instance variables, instance, and static methods.

Multiple instances of a helper class can exist in our application. When different classes have common functionalities, we can group these functionalities together to form a helper class that’s accessible across certain classes in our application.

2.1. How to Create a Java Helper Class

We’ll create an example helper class to understand the concept further.

To create a helper class, we use a default access modifier for our class name. The default access modifier ensures that only classes within the same package have access to this class, its methods, and variables:

class MyHelperClass {

    public double discount;

    public MyHelperClass(double discount) {
        if (discount > 0 && discount < 1) {
            this.discount = discount;
        }
    }

    public double discountedPrice(double price) {
        return price - (price * discount);
    }

    public static int getMaxNumber(int[] numbers) {
        if (numbers.length == 0) {
            throw new IllegalArgumentException("Ensure array is not empty");
        }
        int max = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        return max;
    }

    public static int getMinNumber(int[] numbers) {
        if (numbers.length == 0) {
            throw new IllegalArgumentException("Ensure array is not empty");
        }
        int min = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < min) {
                min = numbers[i];
            }
        }
        return min;
    }
}

After defining the class, we can add as many related instance and static methods as needed.

Helper classes can have instance methods because they can be instantiated.

As seen from the code snippet above, we have both an instance and a static method in MyHelperClass:

@Test
void whenCreatingHelperObject_thenHelperObjectShouldBeCreated() {
    MyHelperClass myHelperClassObject = new MyHelperClass(0.10);
    assertNotNull(myHelperClassObject);
    assertEquals(90, myHelperClassObject.discountedPrice(100.00));

    int[] numberArray = {15, 23, 66, 3, 51, 79};
    assertEquals( 79, MyHelperClass.getMaxNumber(numberArray));
    assertEquals(3, MyHelperClass.getMinNumber(numberArray));
}

From the test, we can see that a helper object was created. Static methods within the helper class are accessed via the class name.

3. Java Utility Classes

A utility class in Java is a class that provides static methods that are accessible for use across an application. The static methods in utility classes are used for performing common routines in our application.

Utility classes cannot be instantiated and are sometimes stateless without static variables. We declare a utility class as final, and all its methods must be static.

Since we don’t want our utility classes to be instantiated, a private constructor is introduced. Having a private constructor means that Java won’t create a default constructor for our utility class. The constructor can be empty.

The purpose of a utility class is to provide methods for executing certain functionalities within a program, while the main class focuses on the core problem it solves.

Methods of a utility are accessed via the class name. It makes our code more flexible for use while remaining modular.

Java has utility classes such as java.util.Arrays, java.lang.Math, java.util.Scanner, java.util.Collections, etc.

3.1. How to Create a Java Utility Class

Creating a utility class is not so different from how we create a helper class. A few things are done a little differently when creating a utility class.

To create a utility class, we use a public access modifier and also declare the class as final. The final keyword used when creating utility classes means that the class would remain unchangeable. It cannot be inherited or instantiated.

Let’s create a utility class called MyUtilityClass:

public final class MyUtilityClass {

    private MyUtilityClass(){}

    public static String returnUpperCase(String stringInput) {
        return stringInput.toUpperCase();
    }

    public static String returnLowerCase(String stringInput) {
        return stringInput.toLowerCase();
    }

    public static String[] splitStringInput(String stringInput, String delimiter) {
        return stringInput.split(delimiter);
    }

}

Another rule to observe is that all methods of a utility class are static, with a public access modifier.

Since we have only static methods within utility classes, these methods can only be accessed via the class name:

@Test
void whenUsingUtilityMethods_thenAccessMethodsViaClassName(){
    assertEquals(MyUtilityClass.returnUpperCase("iniubong"), "INIUBONG");
    assertEquals(MyUtilityClass.returnLowerCase("AcCrA"), "accra");
}

The returnUpperCase() and returnLowerCase() methods in the utility class are only accessed by its caller through the class name, as seen above.

4. Java Helper vs. Utility Classes

Helper and utility classes in Java generally have the same purpose. A utility class is a general-purpose helper class. Developers sometimes use the terms interchangeably.

This is so because they complement other classes by providing methods that handle certain tasks that are not core functionalities of the application.

Though they’re very similar, there exist some subtle differences between them:

  • Helper classes can be instantiated, while utility classes cannot be instantiated because they have a private constructor.
  • Helper classes can have instance variables and also have both instance and static methods.
  • Utility classes only have static variables and methods.
  • Utility classes often have a global scope within our application, while helper classes are always given a package scope.

5. Conclusion

In this article, we examined what helper and utility classes are in Java. We also discovered that helper and utility classes are very much alike in nature because of how they are used in applications.

We went into detail on how to create either a helper or utility class.

When creating robust applications in Java, we should always remember to group similar but independent methods that perform repetitive tasks into a helper or utility class. Sometimes software engineers and developers creating utility or helper classes go against Java’s object-oriented programming paradigm. However, they make our codebase very modular and reusable.

As always, the code for this tutorial can be found over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.