Java Program to Check Whether a Number is Prime or Not

In this example, You learn about Java program to check Prime Number. 

Here you learn check prime of number in Java, You are given a number N and the task of the program to prime check in Java.

prime number java



A prime number is a natural number and that is greater than 1. Prime Number is divisible by 1 or itself. Therefore, Any number divisible by any other number instead of 1 and itself is not a prime number. 

0 and 1 are not considered as a prime numbers. 

Java Program to check Prime of Number



import java.util.*;

public class Main{
  
    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int n;
        boolean flag = false;
        n = scn.nextInt();
        int count  = 0;
        for(int i = 2; i*i <=n ;i++){
            if(n%i == 0){
                count++;
                break;
            }
        }
            
        if(count == 0){
            System.out.println("prime");
        }
        else{
            System.out.println("not prime");
        }
    }
}

Output


 12
 not prime


In the above article, I shared Java program to check Prime Number. If you know something new then please comment or send mail to featured and for contribution to codeamy.in and I also share java program soon.


Happy Coding!! 😊

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form