Modulus &
Remainders
Master the % operator in Java: understand how division produces remainders, and learn to harness them for even/odd checks, cyclic patterns, and digit extraction.
What Is the Modulus Operator?
In Java, the % operator (called "modulus" or "mod") returns the remainder after integer division. If you divide \( a \) by \( b \), the quotient is \( a / b \) and the leftover is \( a \% b \).
Think of it like sharing cookies: if you have 17 cookies and 5 friends, each friend gets \( 17 / 5 = 3 \) cookies, and you have \( 17 \% 5 = 2 \) cookies left over.
Visualizing \( 17 \% 5 \)
Why Modulus Matters in Java
The Core Rule of \( \% \)
Sign Rules: Negative Numbers
In Java, the sign of the result of \( a \% b \) always follows the sign of the dividend (\( a \)), regardless of the sign of \( b \).
| Expression | \( a / b \) | \( a \% b \) |
|---|---|---|
| \( 7 \% 3 \) | 2 | 1 |
| \( -7 \% 3 \) | -2 | -1 |
| \( 7 \% (-3) \) | -2 | 1 |
| \( -7 \% (-3) \) | 2 | -1 |
\( \% \) vs \( / \): Key Distinction
How to Apply \( \% \) Step by Step
Example 1: Even or Odd?
Write a method that returns true if a number is even.
Example 2: Extract the Last Digit
Using \( n \% 10 \) pulls out the ones place of any integer.
Example 3: Cyclic Wrapping
When an index reaches the end of an array, mod wraps it back to the start. This is the basis of circular buffers and round-robin scheduling.
Real-World: 24-Hour Time
A 24-hour clock is a perfect example of modular arithmetic. If it's 22:00 (10 PM), what time will it be in 5 hours?
Classic Pattern: FizzBuzz
The most famous coding interview question combines two modulus checks:
Example 4: Sum of Digits
Use \( \% 10 \) and \( / 10 \) in a loop to peel off digits one at a time:
Common Mistakes
n % 0 throws an ArithmeticException at runtime. Always guard against zero divisors.n % 2 == 1 fails for negative numbers since \( -3 \% 2 = -1 \). Use n % 2 != 0 instead.Modulus Cheat Sheet
| Pattern | Expression | Result |
|---|---|---|
| Even check | \( n \% 2 == 0 \) | true/false |
| Last digit | \( n \% 10 \) | 0..9 |
| Cyclic wrap | \( i \% \text{length} \) | 0..length-1 |
| Divisibility | \( n \% k == 0 \) | true/false |
| Remove last digit | \( n / 10 \) | truncated int |
| 24-hour time | \( (h + d) \% 24 \) | 0..23 |
Question 1 of 5
What is the value of \( 23 \% 7 \) in Java?
Question 2 of 5
What does \( -13 \% 5 \) evaluate to in Java?
Question 3 of 5
Which expression correctly checks if an integer n is odd, even when n is negative?
n % 2 == 1 fails for negative odd numbers (e.g., \( -3 \% 2 = -1 \), not 1). Using n % 2 != 0 catches both \( 1 \) and \( -1 \).Question 4 of 5
Given int[] arr = {10, 20, 30};, what does arr[7 % 3] evaluate to?
Question 5 of 5
What is the output of the following code?