
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements