This post shows a Java program to check whether the passed number is a prime number or not.

A number is a prime number if can be divided either by 1 or by the number itself. So the logic for your program should be to run a for loop and divide the passed number every time in that loop, if it *completely divides any time then the passed number is not a prime number*. You only need to run your loop from 2 till N/2 (where N is the passed number), reason being no number is completely divisible by a number more than its half.

#### Java program to check whether the number is prime or not

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.Scanner; public class PrimeNumChecker { public static void main(String[] args) { // Using Scanner class to take input Scanner sc = new Scanner(System.in); System.out.println("Enter number - "); int num = sc.nextInt(); boolean flag = isNumberPrime(num); if(flag){ System.out.println(num + " is a prime number"); }else{ System.out.println(num + " is not a prime number"); } } private static boolean isNumberPrime(int num){ boolean flag = true; for(int i = 2; i < num/2; i++){ // No remainder means completely divides if(num % i == 0){ flag = false; break; } } return flag; } } |

__Output__

1 2 3 4 5 6 7 |
Enter number - 7 7 is a prime number Enter number - 10 10 is not a prime number |

That’s all for the topic **Java Program to Check Whether Number is Prime or Not**. If something is missing or you have something to share about the topic please write a comment.

**You may also like**

Thanks for tnis interesting post, I hzve shared it on Facebook.