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

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__

Enter number - 7 7 is a prime number Enter number - 10 10 is not a prime number

**Related Posts**

- Check Given Number Palindrome or Not in Java
- Fibonacci Series Java Program
- Java Program to Check if Armstrong Number
- How to Convert int to String in Java
- Java Program to Find Longest Palindrome in The Given String
- Java Program to Check if The Given Strings Are Anagram or Not
- Java Program to Find Common Element Between Two Arrays
- How to Create a Deadlock in Java

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.