Java program to check if a given number is prime or not

This Java program checks whether a given number is prime or not. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.


Java Code:

import java.io.*;
public class PrimeCheck {    
    // Function to check if a number is prime
    public static boolean isPrime(int num) {
        // Corner cases: 0, 1 and negative numbers are not prime
        if (num <= 1) {
            return false;
        }
        // Check divisibility from 2 to square root of the number
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        // If no divisor is found
        // the number is prime
        return true;
    }
    public static void main(String[] args) {
        int num = 17;
        if (isPrime(num)) {
            System.out.println(num + " is a prime number.");
        } else {
            System.out.println(num + " is not a prime number.");
        }
    }
}

Output : 
17 is a prime number.

Explanation:

  • The isPrime() method takes an integer num as input and returns true if the number is prime and false otherwise.
  • We first handle corner cases: 0, 1 and negative numbers are not prime, so we return false for such cases.
  • We iterate from 2 to the square root of the number (i * i <= num).If num is divisible by any number in this range (num % i == 0) then it is not prime and we return false.
  • If no divisor is found in the range, the number is prime and we return true.
  • In the main() method, we test the isPrime() function with a sample number (num = 17).
  • Depending on the result. we print whether the number is prime or not.