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

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022