codescracker


java

Java Program to Check Prime or Not



« Previous Program Next Program »


Check Prime or Not

To check whether the input number is a prime number or not a prime number in Java programming, you have to ask to the user to enter the number and start checking for prime number. If number is divisible from 2 to one less than that number, then the number is not prime number otherwise it will be a prime number.

Java Programming Code to Check Prime or Not

Following Java Program ask to the user to enter the number to check whether it is a prime number or not, then display it on the screen:

Java Programming Example Output:
/* Java Program Example - Check Prime or Not */
		
import java.util.Scanner;

public class JavaProgram
{
    public static void main(String args[])
    {
        int num, i, count=0;
        Scanner scan = new Scanner(System.in);
		
        System.out.print("Enter a Number : ");
        num = scan.nextInt();
		
        for(i=2; i<num; i++)
        {
            if(num%i == 0)
            {
                count++;
                break;
            }
        }
        if(count == 0)
        {
            System.out.print("This is a Prime Number");
        }
        else
        {
            System.out.print("This is not a Prime Number");
        }
    }
}

When the above Java Program is compile and executed, it will produce the following output. Above Java Programming Example Output (for prime number):

Java Program check prime or not

Above Java Programming Example Output (for not prime number):

check prime number in java

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test