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

  1. The % operator gives the remainder of division
  2. number % 2 gives 0 for even, 1 for odd
  3. Compare remainder != 0 to check if odd

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler