How to create your own helper class in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Updated on 26-Jun-2020 07:26:54

Advertisements