Java program to check prime number

Here is a java program to check prime number. This program is take input from user an give output as Prime or Not Prime.

Source Code:

//Java program to check prime number
import java.util.Scanner;
public class checkPrime {
    public static void main(String s[]) {
        Scanner sc = new Scanner(System.in);
        try{
		System.out.println("Enter no. to check:");
		int num = sc.nextInt();
		int flag = 0;
		for(int i = 2; i < num; i++) {
			if(num % i == 0) {
				System.out.println("Not prime!");
				flag = 1;
				break;
			}
		}
		if(flag == 0) {
			System.out.println("Prime!");
		}
	} 
	finally {
		sc.close();
	}
    }
}

Input & Output:

Enter no. to check:
71
Prime!

Recommended Post