Java Programs

Prime number program

In Java, we will learn how to write a program to check whether a given integer is a prime number or not, in the Java programming language.

How will our Java program work?

Our Java program will take an integer as input.

Suppose someone enters the number 5 (as we know, 5 is a prime number), our program will give the output “the given number is a prime number”.

And if someone enters 8, then the output will be “the given number is not a prime number”.

Program:

import java.util.*;  

class Main {
    public static void main(String ...a){
    int i=0,temp=0;
    Scanner sc= new Scanner(System.in);
    System.out.print("Enter number- ");  
    int n= sc.nextInt(); 
 
    for(i=2;i<=(n/2);i++){
		if(n%i==0)
		{
		temp=1;
		break;
		}
	}

	if(temp==1)
	    System.out.println("Number is not a prime");
	else
		System.out.println("Number is prime");
	}
} 

Output:

Enter number- 5
Number is prime

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs