Java program to check prime number

In this tutorial, we will learn how to write a Java program to check whether a number is prime or not.

Java program to check prime number

package com.javaguides.java.tutorial;

import java.util.Scanner;

/**
 * Java program to check prime number
 * 
 * @author https://www.sourcecodeexamples.net/
 *
 */
public class JavaProgram {
    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            boolean isPrime = true;
            System.out.println("Enter any number:");
            // capture the input in an integer
            int num = scanner.nextInt();
            for (int i = 2; i <= num / 2; i++) {
                int temp = num % i;
                if (temp == 0) {
                    isPrime = false;
                    break;
                }
            }
            // If isPrime is true then the number is prime else not
            if (isPrime) {
                System.out.println(num + " is a Prime Number");
            } else {
                System.out.println(num + " is not a Prime Number");
            }
        }
    }
}
Output:
Enter any number:
17
17 is a Prime Number

Related Java Programs


Comments