Check if the Number is Even or Odd in Java

In this tutorial, you will learn to check if the number is even or odd in Java.  In this example program, we will divide the number by 2, and if the remainder is zero, it is an even number.

We will use the modulo operator (%) that returns the remainder of the two numbers after division.

Example

public class Test {

  public static void main(String[] args) {

    int num = 8;
    int num2 = 9;

    if(num % 2 == 0) {
      System.out.println("num is an even number!");
    } else {
      System.out.println("num is odd number!");
    }

    if(num2 % 2 == 0) {
      System.out.println("num2 is an even number!");
    } else {
      System.out.println("num2 is odd number!");
    }

  }
}
Output: num is an even number! num2 is odd number!
 
We can also use the ternary operator to check if the number is even or odd in Java:
public class Test {

  public static void main(String[] args) {

    int num = 112;

    System.out.println(num % 2 == 0 ? true : false);
  }
}
Output: true
 
That was all about how to check if the number is even or odd in Java!

Leave a Reply

Your email address will not be published.