Table of Contents
Java program to check prime number
Prime number is a number which is only divisible by itself or by one. Following Java program will help to understand the logic to check whether the number is prime or not.
Program to check whether number is prime or not in Java
import java.util.*;
class Prime
{
public static void main(String agr[])
{
int num;
boolean p = true;
Scanner in = new Scanner(System.in);
System.out.println("Enter any number : ");
num = in.nextInt();
if(num == 1)
{
System.out.println("1 is not a prime or composite number");
}
for(int i=2; i <= num/2; i++)
{
if(num % i == 0)
{
p = false;
System.out.println(num+" is not a prime number");
break;
}
}
if(p)
{
System.out.println(num+" is a prime number");
}
}
}
Output :
Enter any number :
19
19 is a prime number
—————————————–
Enter any number :
18
18 is not a prime number
PRACTICALS/PRACTICE PROGRAM IN Java
CHECKOUT OTHER RELATED TOPICS
We are aiming to explain all concepts of Java in easiest terms as possible.

ITVoyagers
Author