Prime Number Program in Java

 

Program to find that given number is prime or not.

/**
 * This program is used to find that given number is prime or not.
 * @author javawithease
 */
 
public class PrimeNumber {
      /**
       * This method is used to find that given number is prime or not.
       * @param num
       */
      static void primeNumber(int num){
            int count = 0;
            //0 and 1 are not prime numbers.
            if(num == 0 || num == 1){
                  System.out.println(num + " is not prime.");
            }else{
                  for(int i = 1; i <= num/2; i++){
                        if(num % i == 0){
                              count++;
                        }
                  }
                  if(count > 1){
                        System.out.println(num + " is not prime.");
                  }else{
                        System.out.println(num + " is prime.");
                  }
            }
      }    
 
      public static void main(String args[]){
            //method call
            primeNumber(37);
      }
}

Output:

37 is prime.

Download this example.