Check Prime Number in Java
Here you will learn and get the program code to Check Prime Number in Java programming.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Example to Check Prime Number in Java
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 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PrimeCheck{ public static void main(String[] args) throws IOException { // Create BufferedReader object for input number BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a number: "); int number = Integer.parseInt(reader.readLine()); reader.close(); // Check if number is prime int i; for (i = 2; i * i <= number; i++) { if (number % i == 0) { break; } } // Display result if (i * i > number) { System.out.println(number + " is a prime number."); } else { System.out.println(number + " is not a prime number."); } } } |
Output
C:\CodeRevise\java>javac PrimeCheck.java
C:\CodeRevise\java>java PrimeCheck
Enter a number: 12
12 is not a prime number.
C:\CodeRevise\java>java PrimeCheck
Enter a number: 7
7 is a prime number.
Check out our other Java Programming Examples