How to Check If a Number is Even or Odd Using if-else in Java

In Java programming, it is often necessary to determine whether a given number is even or odd. This tutorial will guide you through the process of writing a simple program to check if a number is even or odd using the if-else statement. By the end of this tutorial, you will have a clear understanding of how to implement this logic in your Java programs.

Understanding Even and Odd Numbers

An even number is defined as a number that is divisible by 2 without leaving a remainder. On the other hand, an odd number is not divisible by 2 without leaving a remainder. For example, 2, 4, 6, and 8 are even numbers, while 1, 3, 5, and 7 are odd numbers.

Writing the Program

public class EvenOddChecker {
public static void main(String[] args)
 {
int number = 17;   
 if (number % 2 == 0) 
{
        System.out.println(number + " is even.");
    } else
{
        System.out.println(number + " is odd.");
    }
}
}

Syntax Explanation

  • The modulus operator % calculates the remainder of dividing the number by 2.
  • If the remainder is equal to 0, the number is even, and the code inside the if block will be executed.
  • If the remainder is not equal to 0, the number is odd, and the code inside the else block will be executed.

Conclusion

In this tutorial, we learned how to check whether a number is even or odd using the if-else statement in Java. By utilizing the modulus operator, we were able to determine if a number is divisible by 2 without leaving a remainder. This simple logic can be applied in various scenarios, such as filtering and categorizing numbers in your programs. With the knowledge gained from this tutorial, you can confidently implement this functionality in your Java projects.

Remember to practice writing and running the code yourself to reinforce your understanding of the concepts discussed. Happy coding!