TechByteByByte

Check if a Number is Even or Odd in Java

A classic QA/automation coding warm-up: determine whether an integer is even or odd in Java, covering the modulo approach, the bitwise trick, and common pitfalls with negative numbers.

#Java#Basics#Modulo Operator#Bitwise Operator#Easy

Category: Easy | Concepts used: Modulo operator, Bitwise AND


Problem Statement

Given an integer n, determine whether it is even or odd.

  • An even number is exactly divisible by 2 (leaves a remainder of 0 when divided by 2).
  • An odd number is not divisible by 2 (leaves a remainder of 1 or -1 when divided by 2).
Input : n = 8        Input : n = 7        Input : n = -3
Output: Even          Output: Odd           Output: Odd

Examples (with edge cases)

#Input nOutputWhy
110Even10 % 2 == 0
27Odd7 % 2 == 1
30Even0 ÷ 2 = 0 with no remainder; division by zero is undefined
4-5OddJava’s % keeps the sign of the dividend → -5 % 2 == -1
5-8Even-8 % 2 == 0

⚠️ Common Beginner Mistake

Java’s % does not behave like mathematical modulo for negative numbers — it keeps the sign of the dividend (the number being divided).

CheckExpressionResultSafe to use?
Wrongn % 2 == 1 → “is odd”-3 % 2 = -1 (not 1!)Fails silently for negative odd numbers
Rightn % 2 == 0 → “is even”-3 % 2 = -1 (not 0!) → correctly OddAlways safe

Takeaway: Always test for even (== 0) and treat everything else as odd, or write n % 2 != 0 to check for odd. Never test == 1 for odd.


Before You Code: Clarify the Contract

Before choosing an algorithm, confirm whether zero and negative values are allowed, how large the input can be, and what should happen when an arithmetic result exceeds the chosen Java type. The examples use the contract stated in this article, but an interview answer should say these assumptions aloud.

Analogy: Pairing Up at a Dance

Imagine you are organizing a dance party. If you have n guests:

  • Even: Every guest can find a dance partner. No one is left standing alone.
  • Odd: One guest is left without a partner, standing by themselves in the corner.

Checking n % 2 == 0 or n & 1 == 0 is simply checking whether there is a lonely guest left over after pairing everyone up!


Solution 1 — Using the Modulo Operator (%)

The most intuitive approach: divide by 2 and look at the remainder.

Intuition

Every number is either a multiple of 2 (even) or one step away from a multiple of 2 (odd). Dividing by 2 and checking the remainder tells you exactly which group it falls into — remainder 0 means it divided perfectly (even), any other remainder means it didn’t (odd).

public class EvenOdd {
    public static String checkEvenOdd(int n) {
        // If remainder when divided by 2 is 0 -> even, else odd
        if (n % 2 == 0) {
            return "Even";
        } else {
            return "Odd";
        }
    }

public static void main(String[] args) {
        System.out.println(checkEvenOdd(10));  // Even
        System.out.println(checkEvenOdd(7));   // Odd
        System.out.println(checkEvenOdd(-5));  // Odd
        System.out.println(checkEvenOdd(0));   // Even
    }
}

Output:

Even
Odd
Odd
Even

Dry Run (n = 7)

n = 7
7 % 2  =>  7 divided by 2 = 3 remainder 1
condition: 1 == 0 ?  -> false
=> goes to else -> "Odd"

Interviewer Insights

This is the standard, readable solution. Interviewers use this question mainly as a warm-up to check comfort with basic operators and edge cases (negative numbers, zero).

Follow-up questions you might get:

  • “What does -7 % 2 evaluate to in Java, and why?”-1, because Java’s % is a remainder operator that preserves the sign of the dividend (unlike Python’s %, which returns a result with the sign of the divisor).
  • “Can you do this without the modulo operator?” → Yes, using bitwise operations (Solution 2).

Solution 2 — Using Bitwise AND (&) — A Bit-Level Alternative

Every even number has its last bit (Least Significant Bit - LSB) as 0, and every odd number has its last bit as 1. We can check just that one bit. In modern Java, this should be treated as an alternative representation of the idea, not as a guaranteed real-world speed improvement over the clearer modulo expression; the compiler and processor can optimize simple arithmetic.

Intuition

In binary, every bit position represents a power of 2 (1, 2, 4, 8, 16…) except the very last bit, which represents 1. Every other bit contributes an even amount to the total sum. Therefore, a number’s “evenness” is decided entirely by whether that last bit is 0 or 1. n & 1 isolates that last bit and throws away everything else.

public class EvenOddBitwise {
    public static String checkEvenOdd(int n) {
        // n & 1 checks only the last bit of n
        // last bit 0 -> even, last bit 1 -> odd
        return (n & 1) == 0 ? "Even" : "Odd";
    }

public static void main(String[] args) {
        System.out.println(checkEvenOdd(10));  // Even
        System.out.println(checkEvenOdd(7));   // Odd
        System.out.println(checkEvenOdd(-5));  // Odd
    }
}

Output:

Even
Odd
Odd

Dry Run (n = 10)

n = 10  -> binary: 1010
1 (mask) -> binary: 0001

1010  (10)
& 0001  (1)
------
  0000  => result = 0 => Even

Dry Run (n = -5, two’s complement)

For negative numbers, Java stores them in two’s complement. The bitwise AND correctly handles negative numbers too:

ValueBinary Representation (32-bit simplified to 8-bit for readability)
-51 1 1 1 1 0 1 1
1 (mask)0 0 0 0 0 0 0 1
AND (&) →0 0 0 0 0 0 0 1 (Result = 1 -> Odd)

📊 Visual Flowchart

graph TD
    Start["Given Integer n"] --> Check{"Choose Approach"}
    Check -->|Modulo %| Mod{"n % 2 == 0?"}
    Check -->|Bitwise &| Bit{"(n & 1) == 0?"}
    Mod -->|Yes| Even["Even Number"]
    Mod -->|No| Odd["Odd Number"]
    Bit -->|Yes| Even
    Bit -->|No| Odd

Final Verdict — Which Solution Should You Give?

Start with Solution 1 (%) as it is highly readable and universal. If the interviewer asks for optimization or follow-ups, introduce Solution 2 (&) and explain the binary representation.


Quick Recap

ApproachTime ComplexitySpace ComplexityHandles Negatives?Interview Signal
n % 2 == 0(O(1))(O(1))YesStandard, clean, highly readable
n & 1(O(1))(O(1))YesAdvanced, demonstrates bit-level CPU execution knowledge
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed