Java program to check even or odd number


How to check if a number is even or odd in Java

This is another basic if-else example for those who are new to Java. The program shows the syntax and basic use of the if-else statement. It is also an example of use of the remainder operator %, also known as modulus operator or mod.
This Java program asks the user to input an integer and then cheks if that number is even or odd using the remainder operator %. The % operator returns the division remainder from two numbers. A number is even if it can be divided by two with no remainder. A number is odd if it has a remainder when divided by two.
For instance: 
6 % 2 = 0 => 6 is an even number 
7 % 2 = 1 => 7 is an odd number. 
If the remainder from division is 0 the number is even, if the remainder is 1 the number is odd.

Java if-else statement to check if a number is even or odd:
if(number % 2 == 0){
  // the number is even               
}else{
  // the number is odd
}
Java program to check even or odd:
import java.util.Scanner;
public class EvenOrOdd {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n;
        System.out.print("Enter an integer number: ");
        n = input.nextInt();
        if(n % 2 == 0){
            System.out.println(n + " is an even number");                                                         
        }else {
            System.out.println(n + " is an odd number");
        }
    }
}
Sample output 1:
Enter an integer number: 7
7 is an odd number
Sample output 2:
Enter an integer number: 12
12 is an even number


No comments :

Post a Comment