Open In App

How to Create Your Own Helper Class in Java?

Last Updated : 06 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, a Helper class is a class that contains useful methods which make common tasks easier, like error handling, checking input, etc. This class intends to give a quick implementation of basic functions so that the programmers do not have to implement them again and again. This class is easy to access as all the member functions are static, means it can be accessed from anywhere. It implements the most commonly used functions, excluding the functions that are already present in the Java library. Different helper classes contain different methods depending on the need of the program.

Features of Helper Class:

  • This class contains common methods that we can use throughout the program.
  • The methods are static, which simply means we can access them without creating an object.
  • We can add methods to a Helper class based on our needs.
  • Grouping related methods together in a Helper Class makes the code more organized.

Note: Make a package for this class, naming HelperClass, and import it in your Java code

Creating a Helper Class

Now, we are going to discuss an example of a Helper class.

Example:

Java
// Java program to demonstrate helper class
import java.lang.*;
import java.util.*;

// Helper class
class HelperClass {

    // to check whether integer is greater than 0 or not
    public static boolean isValidInteger(int test) {
        return (test >= 0);
    }

    // to check whether integer is greater than the lower
    // bound and lower than the highest bound.
    public static boolean isValidInteger(int test, int low, int high) {
        return (test >= low && test <= high);
    }

    // used when we want the user to input the number
    // exactly greater than the lower bound
    public static int getInRange(int low) {
        Scanner sc = new Scanner(System.in);
        int test;
        do {
            test = sc.nextInt();
        } while (test < low);
        
        // Consider closing the scanner when done
        sc.close();
        
        return test;
    }

    // used when we want the user to input the number
    // exactly greater than lower bound and lower than
    // the highest bound
    public static int getInRange(int low, int high) {
        Scanner sc = new Scanner(System.in);
        int test;
        do {
            test = sc.nextInt();
        } while (test < low || test > high);
        
        sc.close();
        
        return test;
    }

    // to check whether an array contains any negative value
    public static boolean validatePositiveArray(int[] array, int n) {
        for (int i = 0; i < n; i++)         
            if (array[i] < 0) 
                return false;        
        return true;
    }

    // to check whether an array contains any positive value
    public static boolean validateNegativeArray(int[] array, int n) {
        for (int i = 0; i < n; i++)
            if (array[i] > 0) 
                return false;
        return true;
    }

    // check whether every element in the array is greater
    // than the lower bound
    public static boolean checkRangeArray(int[] array, int n, int low) {
        for (int i = 0; i < n; i++)        
            if (array[i] < low)
                return false;
        return true;
    }

    // check whether every element in the array is greater
    // than the lower bound and lower than the highest bound
    public static boolean checkRangeArray(int[] array, int n, int low, int high) {
        for (int i = 0; i < n; i++)        
            if (array[i] < low || array[i] > high)             
                return false;
        return true;
    }


    // check whether two given sets as "arrays" are equal or not
    public static boolean isEqualSets(int[] array1, int n, int[] array2, int m) {
        if (n != m)         
            return false;
        
        // Using HashSet instead of HashMap to track unique elements
        HashSet<Integer> set1 = new HashSet<>();
        HashSet<Integer> set2 = new HashSet<>();
        
        for (int i = 0; i < n; i++) 
            set1.add(array1[i]);
        for (int i = 0; i < m; i++) 
            set2.add(array2[i]);

        return set1.equals(set2);
    }

    // calculating factorial of a number
    public static String factorial(int n) {
        String fact = "";
        int res[] = new int[500];
    
        res[0] = 1;
        int res_size = 1;
    
        for (int x = 2; x <= n; x++)
            res_size = multiply(x, res, res_size);
    
        for (int i = res_size - 1; i >= 0; i--)
            fact += Integer.toString(res[i]);
    
        return fact;
    }

    // Multiply x with res[0..res_size-1]
    public static int multiply(int x, int res[], int res_size) {
        int carry = 0;    
        for (int i = 0; i < res_size; i++) {
            int prod = res[i] * x + carry;
            res[i] = prod % 10;    
            carry = prod / 10;
        }
        while (carry != 0) {
            res[res_size] = carry % 10;
            carry = carry / 10;
            res_size++;
        }
        return res_size;
    }

    // Checks whether the given number is prime or not
    public static boolean isPrime(int n) {
        if (n == 2) 
           return true;
        
        int squareRoot = (int)Math.sqrt(n);    
        for (int i = 2; i <= squareRoot; i++)   
          if (n % i == 0) 
             return false;
        return true;
    }

    // Returns nthPrimeNumber
    public static int nthPrimeNumber(int n) {
        int k = 0;
        for (int i = 2;; i++) {
          if (isPrime(i)) 
              k++;        
          if (k == n) 
              return i;
        }
    }

    // check whether the given string is palindrome or not
    public static boolean isPalindrome(String test) {
        int length = test.length();    
        for (int i = 0; i <= length / 2; i++) 
            if (test.charAt(i) != test.charAt(length - i - 1)) 
               return false;
        return true;
    }

    // check whether two strings are anagram or not
    public static boolean isAnagram(String s1, String s2) {

        // Removing all white spaces from s1 and s2
        String copyOfs1 = s1.replaceAll("\\s", "");
        String copyOfs2 = s2.replaceAll("\\s", "");
    
        if (copyOfs1.length() != copyOfs2.length()) 
            return false;

        // Changing the case of characters of both copyOfs1 and
        // copyOfs2 and converting them to char array
        char[] s1Array = copyOfs1.toLowerCase().toCharArray();
        char[] s2Array = copyOfs2.toLowerCase().toCharArray();

        // Sorting both s1Array and s2Array
        Arrays.sort(s1Array);
        Arrays.sort(s2Array);
    
        // Checking whether s1Array and s2Array are equal    
        return Arrays.equals(s1Array, s2Array);
    }    
}

// class for running the helper class methods
class Geeks {
    public static void main(String[] args) {

        int n = -5;    
        if (HelperClass.isValidInteger(n)) 
            System.out.println("True");
        else 
            System.out.println("False");

        String str = "madam";    
        if (HelperClass.isPalindrome(str)) 
           System.out.println("True");
        else 
           System.out.println("False");        
    }
}

Output
False
True

Explanation:

In the above example, we have created a Helper class and we know that all methods in a Helper class are static, it means we can access those methods directly without creating an object. We have created multiple methods in Helper class, and the list of those methods are listed below:

  • isValidInteger(int test): This method checks if a number is greater than or equal to 0.
  • getInRange(int low): This method prompts the user for a number greater than or equal to the specified low.
  • getInRange(int low, int high): This method asks for number betwenn low and high.
  • validatePositiveArray(int[] array, int n): In this method we are checking if all elements of an array are non-negative.
  • isEqualSets(int[] array1, int n, int[] array2, int m): In this method we are comparing two arays and checks if both the array contains the same elements or not.
  • factorial(int n): In this method we are calculating the factorial of a number and return it as a string.
  • isPrime(int n): In this method we are checking if a number is prime or not.
  • isPalindrome(String test): In this method we are checking if a string is palindrome or not.
  • isAnagram(String s1, String s2): In this method we are checking if two strings are anagram or not.

The Geek class is used to test all these methods with the sample input and then we get the desired output.



Next Article
Article Tags :
Practice Tags :

Similar Reads