1. Home
  2. Java
  3. Java Examples
  4. Check Prime Number

Check Prime Number

Java – Check Prime Number

Write a Java program to check a given number is a prime number or not.

What is a Prime Number?

  • A prime number is a number that is fully divisible by itself or 1 only.
  • Such as 13 is a prime number, it is not fully divisible by any number from 2-12.

You may like:

Example

This is a sample Java program to check 13 is a prime number or not.

Compile and run this program:

javac CheckPrimeNumber.java
java CheckPrimeNumber

Output:

13 is a prime number

Check Prime Number with User Input

The following Java program will prompt a user to input a number and check if the entered number is a prime number.

Compile and run this program:

javac CheckPrimeNumber.java
java CheckPrimeNumber

Output:

Input a number:
13
Yes 13 is a prime number

Again run:

Input a number:
15
No 15 is not a prime number