Java program to check whether the number is a prime number
Overview
Let’s develop a Java program to check whether the number is a prime number or not in this tutorial. A prime number is a number that has no factors other than 1 and itself.
Java Program
Install and launch Java IDE. For example, Eclipse.
Create a Java class PrimeNumber
Add the Java code to the class.
package com.testingdocs.programs;
import java.util.Scanner;
/*********************************************
* Program – PrimeNumber.java
Program Description:
* Java Program to check whether a given number
* is a prime or not
*
* Java Tutorials – www.TestingDocs.com
********************************************/
public class PrimeNumber {
public static void main(String[] args) {
try {
Scanner keyboard = new Scanner(System.in);
System.out.println(“Enter a number :=”);
int n = Integer.parseInt(keyboard.nextLine());
Boolean primeFlag = true;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
primeFlag = false;
break;
}
} // end of for
if (primeFlag)
System.out.println(“Given Number is a
Prime Number”);
else
System.out.println(“Given Number is
Not a Prime number”);
} catch (NumberFormatException nfe) {
System.out.println(” Invalid Input.”);
}
} // end of main
}
Explanation
The prime program does the following things:
- The program prompts and takes the number as input from the user.
- The program runs a for loop that runs from 2 to n/2.
- If a number in the range 2 to n/2 can divide the number without any remainder then it breaks the loop after setting the primeFlag variable to false.
- If no number in the range 2 to n/2 can divide the number without any reminder then the for loop terminates. The primeFlag variable’s value remains true.
- The program displays a message based on the value of the primeFlag variable.
Sample Output
Let’s run the program and check the output. Choose the Run As >> Java Application option to run the Java program.
Enter a number to check if it prime number or not.
Enter a number:=
71
Given Number is a Prime Number
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :