## Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Posted on

# Check if a numer is prime in Java

Check if a numer is prime - Java:

``````
/**
* This class is used to check if a number is prime.
* @author
* @version 1.0
*/
/**
* This method checks if a number is prime.
* @param number the number to check.
* @return boolean true if the number is prime, false otherwise.
*/
public boolean isPrime(int number) {
//Variable to store the result
boolean result = true;
//Check if the number is less than 2
if (number < 2) {
//It is not prime
result = false;
} else {
//Check if the number is divisible by 2 or 3
if (number % 2 == 0 || number % 3 == 0) {
//It is not prime
result = false;
} else {
//Check if the number is divisible by any other number from 5 to sqrt(number)
for (int i = 5; i * i <= number; i += 6) {
if (number % i == 0 || number % (i + 2) == 0) {
//It is not prime
result = false;
break;
}
}
}
}
//Return the result
return result;
}

/**
* One Example
*/
public static void main(String args[]) throws IOException {

//Example 1: It is a prime number.
int number = 7;

//Output 1: It is a prime number.
System.out.println("The number " + number + " is " + (primeNumber.isPrime(number) ? "" : "not ") + "a prime number.");

//Example 2: It is not a prime number.
number = 8;

//Output 2: It is not a prime number.
System.out.println("The number " + number + " is " + (primeNumber.isPrime(number) ? "" : "not ") + "a prime number.");

}
}
``````