Checking If a Number Is Odd or Even in Java

06 May 2023 Balmiki Mandal 0 Core Java

Check if a Number Is Odd or Even in Java

Checking if a number is odd or even can be accomplished in Java by using the modulus operator, which will return the remainder of a division operation. To check if a number is odd or even, you must divide the number by two and check the remainder; if the remainder is 0, the number is even, otherwise it is odd.

To use the modulus operator, you simply need to take the number you’re trying to check and divide it by two. The syntax for this in a Java program would look like this:

int remainder = myNumber % 2;

The remainder of this operation should either be 0 or 1, depending on whether or not the number is even or odd. If you want to print out a message that says the number is even or odd, you can use an if/else statement:

if (remainder == 0) {
  System.out.println("The number is even");
} else {
  System.out.println("The number is odd");
}

And that's all there is to it! You have now learned how to use the modulus operator and an if/else statement to check if a number is odd or even in Java.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.