Java ProgramsControl FlowCheck Even or Odd

Check Even or Odd in Java

beginner·  Control Flow  ·  Conditional Statements

Problem

A number is even when dividing it by 2 leaves no remainder, and odd otherwise.

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

Input
17
Output
17 is odd

Java Program

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

Output

17 is odd

Core Logic

Checking the remainder left over after dividing by 2 separates even numbers from odd ones directly.

How It Works
  1. 1n % 2 == 0 computes the remainder of n divided by 2 and compares it to zero.
  2. 2A remainder of 0 means the number divides evenly, so it's reported as even.
  3. 3Any other remainder — which for the modulo operator can only be 1 or -1 — means the number is odd.
For n = 17, 17 % 2 is 1, not 0, so the number is reported as odd.
💡

Key Point: The remainder from % is the only thing this check needs — there's no separate case for negative numbers, since a nonzero remainder always means odd regardless of sign.

Key Concepts

if/elsemodulo operator

Approach 2: Using Bitwise AND

Java
public class EvenOrOddBitwise { public static void main(String[] args) { int n = 17; // Checks only the lowest bit — 1 means odd, 0 means even boolean isEven = (n & 1) == 0; System.out.println(n + (isEven ? " is even" : " is odd")); } }

Output

17 is odd

Core Logic

Inspecting only the lowest bit of a number's binary representation reveals its parity without needing division at all.

How It Works
  1. 1n & 1 masks out every bit of n except the lowest one.
  2. 2That lowest bit is 0 for every even number and 1 for every odd number, by definition of binary place value.
  3. 3Comparing the masked result to 0 gives the same true/false answer the modulo check produces.
17 in binary is 10001; masking with 1 keeps only the final bit, which is 1, so isEven is false and the number is reported as odd.
💡

Key Point: In Java, (n & 1) == 0 agrees with n % 2 == 0 even for negative numbers, since Java's two's-complement representation keeps that lowest bit accurate regardless of sign — that isn't guaranteed in every language, but it holds here.

Key Concepts

bitwise ANDbinary representation

Related Programs