BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java program to check prime number

Last Updated: September 10, 2022 by Chaitanya Singh | Filed Under: Java Examples

The number which is only divisible by itself and 1 is known as prime number, for example 7 is a prime number because it is only divisible by itself and 1.
This program takes the number (entered by user) and then checks whether the input number is prime or not. The program then displays the result. If you are looking for a program that displays the prime number between two intervals then see: Java program to display prime numbers between 1 to n.

Example: Program to check whether input number is prime or not

To understand this program you should have the knowledge of for loop, if-else statements and break statement.

import java.util.Scanner;
class PrimeCheck
{
   public static void main(String args[])
   {		
	int temp;
	boolean isPrime=true;
	Scanner scan= new Scanner(System.in);
	System.out.println("Enter any number:");
	//capture the input in an integer
	int num=scan.nextInt();
        scan.close();
	for(int i=2;i<=num/2;i++)
	{
           temp=num%i;
	   if(temp==0)
	   {
	      isPrime=false;
	      break;
	   }
	}
	//If isPrime is true then the number is prime else not
	if(isPrime)
	   System.out.println(num + " is a Prime Number");
	else
	   System.out.println(num + " is not a Prime Number");
   }
}

Output:

Enter any number:
19
19 is a Prime Number

Output 2:

Enter any number:
6
6 is not a Prime Number

You can also use while loop to check the prime number:
Just replace this part of the code in above program:

for(int i=2;i<=num/2;i++)
{
   temp=num%i;
   if(temp==0)
   {
      isPrime=false;
      break;
   }
}

with this:

int i=2;
while(i<= num/2)
{
   if(num % i == 0)
   {
	isPrime = false;
	break;
   }
   i++;
}

Top Related Articles:

  1. Java Program to Calculate average using Array
  2. Sunny Number Program in Java
  3. Java Program to reverse the Array
  4. java program to check palindrome string using recursion
  5. Sphenic Number in Java – Check and Print all numbers in a range

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. venkata kalluri says

    May 1, 2014 at 8:19 PM

    The program fails, when i provided the number ‘ 893 ‘ . It is a prime number but the above program shows that it is not a prime. The following program gives the correct answer. However, The loop runs 8 times, irrespective of prime or not prime. In case of the above program, It exit the loop as soon as it is an even number but for odd numbers, the loop will run more number of times.

    Please provide me your feedback(pros/cons) on this program.

    public class PrimeNumber {
    public static void main(String args[]) {
    PrimeNumber p = new PrimeNumber();
    Scanner scan = new Scanner(System.in);
    System.out.println(“Enter a number for check in main method:”);
    int n = scan.nextInt();
    int count = 0;
    int number = 0;
    for (int i = 2; i <= 9; i++) {
    if (n % i == 0) {
    System.out.println(" count called when " + i);
    count = count + 1;
    }
    number = number + 1;
    System.out.println(" The loop called "+number+" times");
    }
    if (count == 0) {
    System.out.println(n + " is a prime number ");
    }
    System.out.println(" ================================ ");
    p.checkPrime();
    }
    }

    Reply
    • lit-el Jon says

      June 17, 2015 at 1:52 AM

      893 is not a prime number it is divisible by 19…

      Reply
      • Sankar says

        November 2, 2016 at 10:09 AM

        Hi friend try this program and give a feedback please,

        public class PrimeNumber {
        public static void main(String args[]) {
        int num=0;
        int prime=0;
        Scanner sc=new Scanner(System.in);
        System.out.println(“Enter the numbe to check”);
        num=sc.nextInt();
        if(num%2==0 && num>=2)
        {
        prime=0;

        }
        else
        {
        prime=1;
        }
        if(prime==0)
        {
        System.out.println(” prime number”);
        }
        else
        {
        System.out.println(” not prime number”);
        }
        }

        }

        Reply
        • Siddhabrata Mohapatra says

          December 28, 2016 at 5:49 AM

          Pls add “import java.util.*;” in the begening

          Reply
        • arun says

          December 30, 2016 at 6:39 PM

          This program is wrong

          Reply
    • sanjeev says

      March 21, 2016 at 1:38 PM

      sorry man 893 divided by 19 by 47 times

      Reply
    • Devikaa Sharma says

      November 9, 2017 at 3:23 PM

      Umm… actually, 893 is not a prime number mate. It is divisible by 19 at 47 times. So maybe that’s why you’re getting an error.

      Reply
  2. venkata kalluri says

    May 1, 2014 at 8:25 PM

    I realized, my program has a bug in it. :-(

    Reply
    • Zaheem says

      November 20, 2021 at 6:23 PM

      Your Logic is not correct!

      Reply
  3. Sayed Asad says

    May 14, 2015 at 4:24 PM

    your example is to complex lets simplify the example of prime

    public static void main(String args[]) {
    int num = new Scanner(System.in).nextInt();
    if (num % 2 == 0) {
    System.out.println(“not prime”);
    } else {
    System.out.println(“Prime”);
    }
    }

    Reply
    • Quack says

      October 15, 2016 at 1:54 PM

      This only checks if the number is even, if you enter 2 which is a prime number, it will consider it as not a prime number..

      Reply
    • kapil kumar says

      September 16, 2021 at 5:41 AM

      try 7919 your program is giving output this is prime but actually is not prime

      Reply
    • amrita raj says

      January 16, 2022 at 3:04 PM

      change(n%2==0) to (n%2==1) then its prime or in else not prime u can print this logic.

      Reply
  4. Ashved says

    August 11, 2015 at 6:41 AM

    Hello i am new to java programming, can somebody explain me this code please ??

    Reply
  5. Hrishi Joshi says

    October 29, 2015 at 9:59 AM

    The program is perfect it runs and also no wrong o/p

    Reply
    • harrisonthu says

      June 19, 2016 at 1:29 AM

      No, I think it does not work if the input number is 1. OP, you need to hardcode to fix the code. if the input is 1.

      Reply
  6. Guest says

    February 18, 2016 at 1:54 PM

    Why do you iterate the for loop to num/2 ?
    “for(int i=2;i<=num/2;i++)"
    Should probably be Math.sqrt(num) instead.

    Reply
    • Guest says

      April 4, 2016 at 10:29 PM

      it is so the program doesn’t allow numbers bellow 4 to enter the for loop. testing the numbers 2 and 3 wouldn’t make sense, because they are prime. However this program allows 1 to be a prime number which is demonstrably false as per the definition of a prime number, so a change to the logic would benefit the people reading this. For example you can get around this by adding the following code:
      if(isPrime == 1)
      {
      isPrime=false;
      }
      this code must be placed before the last if structure and after the for loop.

      Reply
      • Daniel says

        January 22, 2022 at 4:00 AM

        Prime it’s a Boolean statement and it’s not set as an integer so it doesn’t work

        Reply
  7. hitesh kumar says

    May 31, 2016 at 7:16 PM

    what is the role of boolean function here ? please explain .thank you.

    Reply
  8. Degaleesan Pugazhenthi says

    June 11, 2016 at 2:45 PM

    How to identify the prime number count from 1 to 1000 without using the below code. (Required alternative method – should not go one by one and count it)

    int Count=0;
    for(int i=1;i<=1000;i++)
    {
    temp=num%i;
    if(temp==0)
    {
    isPrime=false;
    break;
    }
    }
    //If isPrime is true then the number is prime else not
    if(isPrime){
    System.out.println(num + " is Prime Number");
    Count++;
    }

    Thanks in Advance
    Degaleesan

    Reply
  9. bharti mane says

    April 2, 2017 at 12:35 PM

    for (i=2;i<=num/2;i++)
    i just want yo know why this has been used?

    as per my understanding i=2 means prime has two factors that is 1 and itself.
    i dont know about next part..sir can you please explain

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap