# How To Check Prime Number In Java Programming?

Hi all, hope you are doing good.
In general we think that, finding prime number will be very easy and normally we neglect to refresh this program before attending interview. Even though concepts are same Interviewer may ask same program in many ways. So be prepared while attending interview. Hope below article will clear about possible way of ask to check prime number.

Prime number is a number that is greater than 1 and divided by 1 or itself only. Note that, prime numbers can’t be divided by other numbers than itself or 1.
For example, Prime number from 0 to 100 are, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, and 97.
Note:

• 0 or 1 is not Prime Number.
• 2 is Prime number

### Example 1: Check given number is Prime or not

```import java.util.Scanner;

public static void main(String[] args) {

//Create object for scanner class to fetch input data from keyboard
Scanner scn = new Scanner(System.in);

int inputValue = scn.nextInt();
boolean flag = false;
if (inputValue == 0 || inputValue == 1) {
System.out.println(inputValue+ " is neither PRIME nor COMPOSITE number");
} else {
for (int i = 2; i <= inputValue / 2; i++) {
if (inputValue % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(inputValue+ " is a Prime number");
else
System.out.println(inputValue+ " is NOT a Prime number");
}
}
}
```
``````Output 1:
1 is neither PRIME nor COMPOSITE number

Output 2:
2 is a Prime number

Output 3:
17 is a Prime number

Output 4:
25 is NOT a Prime number``````

### Example 2: Check given range of number is Prime or not

```import java.util.Scanner;

public static void main(String[] args) {
//Create object for scanner class to fetch input data from keyboard
Scanner scn = new Scanner(System.in);
System.out.print("Enter range : ");
int range = scn.nextInt();

if (range == 0 || range == 1) {
System.out.println("Given range is not valid, Please try again !");
}else{
System.out.println("Prime numbers are: ");
for (int inputValue = 0; inputValue <=range; inputValue++) {
if (inputValue == 0 || inputValue == 1) {
continue;
} else {
boolean flag = false;
for (int i = 2; i <= inputValue / 2; i++) {
if (inputValue % i == 0) {
flag = true;
break;
}
}
if (!flag) {
System.out.println(inputValue);
}
}
}
}
}
}
```
``````Output 1:
Enter range : 0
Given range is not valid, Please try again !

Output 2:
Enter range : 2
Prime numbers are:
2

Output 3:
Enter range : 10
Prime numbers are:
2
3
5
7

Output 4:
Enter range : 25
Prime numbers are:
2
3
5
7
11
13
17
19
23``````

Recommended article for you:

Hey, Now it is your time! Drop a comment if more details needed or if any update requires. Your comments are more valuable to improve our site to help others.

### 3 thoughts on “How To Check Prime Number In Java Programming?”

1. I regard something genuinely interesting about your web site so I saved to fav. 