Create Your Own Helper Class in Java



A helper class serve the following purposes.

  • Provides common methods which are required by multiple classes in the project.

  • Helper methods are generally public and static so that these can be invoked independently.

  • Each methods of a helper class should work independent of other methods of same class.

Following example showcases one such helper class.

Example

public class Tester {
   public static void main(String[] args) {
      int a = 37;
      int b = 39;
      System.out.println(a + " is prime: " + Helper.isPrime(a));
      System.out.println(b + " is prime: " + Helper.isPrime(b));
   }
}
class Helper {
   public static boolean isPrime(int n) {
      if (n == 2) {
         return true;
      }
      int squareRoot = (int)Math.sqrt(n);
      for (int i = 1; i <= squareRoot; i++) {
         if (n % i == 0 && i != 1) {
            return false;
         }
         return true;
      }
   }
}

Output

37 is prime: true
39 is prime: false
Updated on: 2020-06-26T07:26:54+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements