In this tutorial, we are going to write a Java program to check whether a given number is a prime number or not in Java Programming with practical program code and step-by-step full complete explanation.
Java program to check prime number
import java.util.Scanner; public class PrimeNumber{ public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int number, m, flag=0; // Enter number System.out.print("Enter number = "); number = scanner.nextInt(); m = number/2; if(number == 0 || number == 1){ System.out.print(number +" is not prime number"); } else { for(int i = 2; i <= m; i++){ if(number % i == 0){ System.out.println(number +" is not prime number"); flag = 1; break; } } if(flag == 0){ System.out.println(number +" is prime number"); } } } }
Output
Enter number = 8 8 is not prime number