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(System.in);
		
		// 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");
		}
		
		sc.close();
	}
}

Output: 

Enter the Number: 
8
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.

Comments

Popular Posts from this Blog

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

LeetCode - Bulb Switcher Solution - The Coding Shala

Anti Diagonals - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala

Java Method Overloading - The Coding Shala