Modulus Operator in Java: Explanation & Practice
Use modulus to get remainder
Problem summary
Check if 17 is even or odd using the modulus operator.
Starter code
public class Main {
public static void main(String[] args) {
int number = 17;
// Use modulus to find remainder when divided by 2
// Print: Number: 17
// Print: Remainder when divided by 2: 1
// Print: Is odd: true
}
}Expected output and test cases
- Check if 17 is odd
Number: 17 Remainder when divided by 2: 1 Is odd: true
Hints
- The % operator gives the remainder of division
- number % 2 gives 0 for even, 1 for odd
- Compare remainder != 0 to check if odd
Related Core Java Basics exercises
- Practice Arithmetic Operations in Java
- Practice String Concatenation in Java
- Practice Sum of Digits in Java
Practice all Core Java Basics exercises · Run this idea in the Java compiler