Prime number program in java

In this tutorial we are going to learn how to write a program to check whether a given integer number is prime number or not in Java programming language.

 

Read this: What is prime number? Prime number program in C.

Our Java program will take one integer number as input.

Suppose if someone gives an input 5 (As we know 5 is Prime number) then our program will give output “given number is a prime number”.

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

Java program to check given number is prime or not

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:

java program to check number is prime or not

Leave a Comment