Explain Codes LogoExplain Codes Logo

Check whether number is even or odd

java
bitwise-operations
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Dec 28, 2024
TLDR

A prompt method to determine if a number is even or odd applies the modulo operator number % 2. An even number will yield a remainder of 0:

boolean isEven = (number % 2) == 0; System.out.println(isEven ? "Even as Sheldon on 73rd take" : "Odd as socks in a dryer");

Just swap in your number for number.

Bitwise operation: the speed demon

The bitwise AND operator (x & 1), while a tad esoteric, can help speed up your even/odd checks:

boolean isEven = (number & 1) == 0; System.out.println(isEven ? "Even as a slow clap" : "Odd for now...");

Considering the least significant bit of an even number is 0 and 1 for odd, this method is not only fast, but also displays your in-depth understanding of binary representation.

Modulo vs Bitwise: a crash course

The Modulo Approach

The modulo operator % finds the remainder after division of one number by another (referred to as the divisor):

int positiveEven = 4; int negativeOdd = -3; System.out.println((positiveEven % 2 == 0) ? "Even!" : "Odd indeed!"); System.out.println((negativeOdd % 2 != 0) ? "Odd, like ducks in a row" : "Even, and it's your move");

Generally, any number yielding 0 with %2 is even.

The Bitwise Approach

The bitwise AND operator & performs a binary AND operation:

int num = 4; boolean isEven = (num & 1) == 0; System.out.println(isEven ? "Even, like a high-stakes game of Go!" : "Odd...similarly intriguing");

With bitwise, we're essentially checking the last digit of the binary representation (least significant bit).

When to use each method: choose your weapon

  • Clarity: The modulo method is generally more recognizable and readable to most developers. Favor this method when readability triumphs.

  • Efficiency: In systems where performance is paramount, the bitwise method might give you the edge.

  • Learning curve: For learners, starting with modulo instills a solid foundation. Later on, bitwise serves as a cool trick up your sleeve.

Cracking the edge cases

Overflow blues

Especially with large numbers, the overflow issue with % may give incorrect results. Never fear, bitwise gracefully sidesteps this.

The case of the negatives

Happily, both methods handle negative numbers accurately. It's advisible to run negative scenarios through your code tests.

Integer divisions’ oddities

Becareful with integer division - look out for accidental use of / instead of %. The former could lead to quotient quandary, not a remainder revelation.

The smallest of them all

The humble 0 is even, and 1 is odd. These edge cases often get overlooked, but could reveal code logic errors.