Blog Archive

Java example code to check if a number is even, odd or prime

package com.as400samplecode;

public class CheckMyNumber {

    public static void main(String[] args) {

        boolean even = false;
        boolean prime = true;
        int myNumber = Integer.parseInt(args[0].trim());

        if(myNumber % 2 == 0){
            even = true;
            prime = false;
        }
        else {
            for(int i=3; i*i<=myNumber; i+=2) {
                if(myNumber % i == 0) {
                    prime = false;
                }
            }
        }

        if(even){
            System.out.println("The given number is Even.");
        }
        else {
            if(prime){
                System.out.println("The given number is Prime.");
            }
            else {
                System.out.println("The given number is Odd.");
            }
        }
    }

}
  • Even number
    • An even number is an integer which is a multiple of two. If it is divided by two the result is another integer. Zero is an even number because zero multiplied by two is zero
  • Odd number
    • An odd number is an integer of the form n=2k+1, where k is an integer. Odd numbers leave a remainder of 1 when divided by two.
  • Prime number
    • A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.