Java Program to Check Whether a Number is Prime or Not

 In this Java program, you’ll learn how to Check Whether a Number is Prime or Not using the Java programming language.    

Prime number– A number that is divisible only by itself and 1 is called prime number. 

How to check whether a Number is Prime or Not using JAVA? 

Example 1: using While loop 

RUN CODE SNIPPET
public class Main { 
  public static void main(String[] args) { 
    int num = 11, i = 2; 
    boolean flag = false; 
    while (i <= num / 2) { 
      if (num % i == 0) { 
        flag = true; 
        break; 
      } 
      ++i; 
    } 
    if (!flag) 
      System.out.println(num + " is a prime number."); 
    else 
      System.out.println(num + " is not a prime number."); 
  } 
}

OUTPUT 

11 is a prime number.

In the above program, we have used while loop. The condition used here is i <= num/2 the loop will run until the condition turns out. 

Example 2: using For loop 

RUN CODE SNIPPET
public class Main { 
  public static void main(String[] args) { 
    int num = 122; 
    boolean flag = false; 
    for (int i = 2; i <= num / 2; ++i) { 
      if (num % i == 0) { 
        flag = true; 
        break; 
      } 
    } 
    if (!flag) 
      System.out.println(num + " is a prime number."); 
    else 
      System.out.println(num + " is not a prime number."); 
  } 
}

OUTPUT 

122 is not a prime number.

In the above program, for loop is used to find out whether the given number is prime or not. 

The condition used here is i <= num / 2, a prime number is not divisible by its half. 

If the number is divisible then it breaks the loop and determines the number is not a prime number. 

If the number is not divisible then it determines that the number is a prime number. 

Share:

Leave A Reply

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

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024