Java Program to Check Prime Number - The Coding Shala

Home >> Java Programs >> Check Prime Number

 In this post, we will learn how to Check if a Given Number is a Prime Number or not in Java.

Java Program to Check Prime Number

A Prime Number is a number that is divisible by 1 and the number itself. For example, the number 5 is a Prime Number because it is divisible by 1 and 5 only. 

Note: Number 0 and 1 are not prime numbers.

Example 1:
Input: 7
Output: Prime Number

Example 2:
Input: 9
Output: Not a Prime Number

Java Program: 

// Java program to Check Prime Number

import java.util.Scanner;

public class Main {
	static boolean isPrime(int num) {
		if(num < 2) return false;
		//  basic for loop ==> for(int i = 2; i < num / 2; i++ )
		for(int i = 2; i * i <= num; i++) {
			if(num % i == 0) return false;
		return true;
	public static void main(String[] args) { 
		Scanner sc = new Scanner(;
		// take input char
		System.out.println("Enter the Number: ");
		int num = sc.nextInt();
		if(isPrime(num)) {
			System.out.println(num + " is a Prime Number");
		} else {
			System.out.println(num + " is not a Prime Number");


Enter the Number: 
8 is not a Prime Number

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala