codescracker
java

Java Program to Check Prime Number or Not



« Previous Program Next Program »

This article is created to cover a program in Java that checks whether a number entered by user is a prime number or not. I've used following two ways to do the job:

Note - A prime number is a number that can only be divisible by 1 and the number itself. For example, 2, 3, 5, 7, 11 etc.

Check Prime Number in Java using for Loop

The question is, write a Java program to check prime number or not using for loop. The number must be received by user at run-time of the program. The program given below is its answer:

import java.util.Scanner;

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

The snapshot given below shows the sample run of above Java program with user input 19:

Java Program check prime or not

Since the number 19 can only be divisible by 1 and the number itself (19) without leaving any remainder, therefore 19 is a prime number.

Check Prime Number in Java using while Loop

This program is created using while loop. Also the program is modified in a way that, it will print the number too along with message saying whether it is a prime or not. Let's have a look at the program given below:

import java.util.Scanner;

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

Here is its sample run with user input 12:

check prime number in java

12 is not a prime number because, except 1 and 12, the number 2, 3, 4, and 6 also divides 12.

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker