Java Program to Check a Number is Prime Number or Not

  • How to check, whether a number is prime number or not.
  • Write a program in Java to check for prime numbers.

We have to check whether given number is prime number or not. First of all, we have to understand fundamentals of prime numbers.

  • A Prime number is a positive number greater than 1 that is only divisible by either 1 or itself.
  • All numbers other than prime numbers are known as composite numbers.
  • Any non-prime number can be expressed as a factor of prime numbers.
  • There are infinitely many prime numbers, here is the list of first few prime numbers
    2 3 5 7 11 13 17 19 23 29 31 37....

Java program to check for prime number

Let N be the number for primality testing. Here, we will use brute force approach by testing whether N is a multiple of any integer between 2 and N/2. This is the most basic method of checking the primality of a given integer N and is called trial division method.
package com.tcc.java.programs;

import java.util.*;

public class PrimeNumberCheck {
    public static void main(String args[]) {
        int num, i, isPrime = 0;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter an Integer");
        num = in.nextInt();

        for(i = 2; i <= (num / 2); ++i) {
            if (num % i == 0) {
                isPrime = 1;
                break;
            }
        }
        // If isPrime is true then the num is prime otherwise non-prime
        if (isPrime == 0)
            System.out.println(num + " is a Prime Number");
        else
            System.out.println(num + " is not a Prime Number");
    }
}
Output
Enter an Integer
23
23 is a Prime Number
Enter an Integer
30
30 is not a Prime Number