Java Program to Check a Number is Prime Number or Not

Here is a java program to check, whether a number is prime number or not. 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 == 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

Recommended Posts
Java Program to Print Prime Numbers between 1 to 100
Java Program to Check Perfect Number or Not
Java Program to Check Whether a Number is Palindrome or Not
Java Program to Check Whether a Number is Armstrong Number or Not
Java Program to Find LCM and GCD of Two Numbers
Java Program to Insert an Element in Array at Given Position
Java Program for Matrix Multiplication
C++ Program to Check Prime Number
C++ Program to Print All Prime Numbers Between 1 to N
Java Program to Calculate Volume of Sphere
Java Program to Check If a Year is Leap Year or Not
All Java Programs