Site icon TestingDocs.com

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:

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 :

https://www.oracle.com/in/java/

Exit mobile version