In this tutorial you will learn about the Java Program to check Prime Number and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Prime Number using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
- User Define functions
What is Prime Number?
A number is called a Prime number if a number is divisible by 1 or itself only.
For example 2, 3, 5, 7, 11, 13, 17..are some prime numbers.
Java Program to check Prime Number
In this program we would find the given number is a Prime Number or not .First of all we take a value form user and find the number is prime or not.Let have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// java program to find Prime number import java.util.Scanner; class PrimeCheck { public static void main(String args[]) { // declaring variables and taking values from user int temp; boolean flag=true; Scanner scan= new Scanner(System.in); System.out.println("Enter any number "); int number=scan.nextInt(); scan.close(); // checking condition for prime for(int i=2;i<=number/2;i++) { temp=number%i; if(temp==0) { flag=false; break; } } // Printing the result if(flag) System.out.println(number + " is a Prime Number"); else System.out.println(number + " is not a Prime Number"); } } |
Output
Prime number
Not a Prime number.
In the above program, we have first declared and initialized a set variables required in the program.
- number= it will hold entered number.
- temp = it will hold temporary number.
- flag= it will hold the result.
- i = for iteration
After declaring variables we take a value from user and find number is prime or not.
with in loop we will find that given number is prime or not where we divide number from 2 to number if number divide by it self only value of flag variable remain true
else set to false it means number is not a prime number
so in this blog we have find the given number is a prime number or not.