Java Program to Check a Number is Prime or Not

In this example, we are giving a program to check whether a number is prime or not.


To check a number is prime or not:

  1. # To check a number is prime or not
  2. public class Prime {
  3. public static void main(String[] args) {
  4. int num = 13;
  5. boolean flag = false;
  6. for(int i = 2; i <= num/2; ++i) {
  7. if (num % i == 0) {
  8. flag = true;
  9. break;
  10. }
  11. }
  12. if (!flag)
  13. System.out.println(num + " is a prime number.");
  14. else
  15. System.out.println(num + " is not a prime number.");
  16. }
  17. }

Output:

13 is a prime number.