PhysicsTeacher.in

High School Physics

Java Program for prime number checking

Let’s see how to write a Java program to accept a number and check whether the number is a Prime number or not.

A prime number is a whole number greater than 1 whose only factors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.

Prime number checking – Java program

import java.util.Scanner;
public class Prime {

public static void main(String[] args) {
int num;
Scanner s = new Scanner(System.in);

System.out.print(“Enter any integer you want to check:”);
num = s.nextInt();
boolean flag = false;

for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number

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.”);

}
}

See also  Palindrome Program in Java using String methods
Scroll to top
error: physicsTeacher.in