How to Check If a Number Is Even in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to determine if a number is even or odd in Java. We will explore the use of the modulo operator (%) to check for a remainder when a number is divided by 2, which is the fundamental principle for identifying even numbers.

You will implement a simple Java program to perform this check, test it with both positive and negative integer inputs, and consider how to handle non-integer inputs to make your solution more robust.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("User Input") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") subgraph Lab Skills java/data_types -.-> lab-559962{{"How to Check If a Number Is Even in Java"}} java/operators -.-> lab-559962{{"How to Check If a Number Is Even in Java"}} java/if_else -.-> lab-559962{{"How to Check If a Number Is Even in Java"}} java/user_input -.-> lab-559962{{"How to Check If a Number Is Even in Java"}} java/exceptions -.-> lab-559962{{"How to Check If a Number Is Even in Java"}} end

Use Modulo Operator for Even Check

In this step, we will learn how to determine if a number is even or odd in Java using the modulo operator. The modulo operator (%) gives you the remainder of a division. For example, 10 % 3 is 1 because 10 divided by 3 is 3 with a remainder of 1.

An even number is any integer that can be divided by 2 with no remainder. This means that if you divide an even number by 2, the remainder is always 0. We can use the modulo operator to check this condition.

Let's create a simple Java program to check if a number is even.

  1. Open the EvenCheck.java file in the WebIDE editor. If the file doesn't exist, create it in the ~/project directory. You can do this by right-clicking in the File Explorer on the left, selecting "New File", and typing EvenCheck.java.

  2. Add the following code to the EvenCheck.java file:

    public class EvenCheck {
        public static void main(String[] args) {
            int number = 10; // We'll check if this number is even
    
            // Use the modulo operator to check for a remainder when divided by 2
            if (number % 2 == 0) {
                System.out.println(number + " is an even number.");
            } else {
                System.out.println(number + " is an odd number.");
            }
        }
    }

    Let's look at the new parts:

    • int number = 10;: This declares an integer variable named number and assigns it the value 10. We can change this value to test different numbers.
    • if (number % 2 == 0): This is an if statement. It checks if the condition inside the parentheses is true. The condition number % 2 == 0 checks if the remainder of number divided by 2 is equal to 0.
    • System.out.println(number + " is an even number.");: This line is executed if the condition in the if statement is true (the number is even).
    • else: This keyword introduces the block of code to be executed if the condition in the if statement is false (the number is odd).
    • System.out.println(number + " is an odd number.");: This line is executed if the number is odd.
  3. Save the EvenCheck.java file (Ctrl+S or Cmd+S).

  4. Now, compile the program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Then, run the following command:

    javac EvenCheck.java

    If there are no errors, a EvenCheck.class file will be created.

  5. Finally, run the compiled program:

    java EvenCheck

    You should see the output indicating whether the number 10 is even or odd.

    10 is an even number.

Now, try changing the value of the number variable in the EvenCheck.java file to a different integer (e.g., 7, -5, 0) and repeat steps 3, 4, and 5 to see how the output changes.

Test with Positive and Negative Numbers

In the previous step, we successfully checked if a positive integer is even or odd. Now, let's explore how the modulo operator works with negative numbers and zero. The concept of even and odd applies to all integers, including negative ones and zero.

An integer is even if it is divisible by 2, meaning the remainder is 0. This definition holds true for negative numbers as well. For example, -4 is even because -4 divided by 2 is -2 with a remainder of 0. -3 is odd because -3 divided by 2 is -1 with a remainder of -1 (or 1, depending on the definition of modulo for negative numbers, but the key is it's not 0). Zero is also considered an even number because 0 divided by 2 is 0 with a remainder of 0.

Let's modify our EvenCheck.java program to test with different positive and negative numbers, as well as zero.

  1. Open the EvenCheck.java file in the WebIDE editor.

  2. Modify the main method to test several different numbers. You can change the value of the number variable multiple times, or you can add more if-else blocks to check different numbers sequentially. For simplicity, let's change the value of number and re-run the program for each test case.

    First, let's test with a positive odd number. Change the line int number = 10; to:

    int number = 7; // Test with a positive odd number
  3. Save the file.

  4. Compile the modified program in the Terminal:

    javac EvenCheck.java
  5. Run the program:

    java EvenCheck

    You should see the output:

    7 is an odd number.
  6. Now, let's test with a negative even number. Change the line int number = 7; to:

    int number = -4; // Test with a negative even number
  7. Save the file.

  8. Compile the program:

    javac EvenCheck.java
  9. Run the program:

    java EvenCheck

    You should see the output:

    -4 is an even number.
  10. Next, test with a negative odd number. Change the line int number = -4; to:

    int number = -3; // Test with a negative odd number
  11. Save the file.

  12. Compile the program:

    javac EvenCheck.java
  13. Run the program:

    java EvenCheck

    You should see the output:

    -3 is an odd number.
  14. Finally, test with zero. Change the line int number = -3; to:

    int number = 0; // Test with zero
  15. Save the file.

  16. Compile the program:

    javac EvenCheck.java
  17. Run the program:

    java EvenCheck

    You should see the output:

    0 is an even number.

As you can see, the modulo operator correctly identifies even and odd numbers for positive, negative, and zero values. The logic number % 2 == 0 is a reliable way to check for evenness for any integer.

Handle Non-Integer Inputs

In the previous steps, we've successfully used the modulo operator to check if integer numbers are even or odd. However, what happens if the user tries to input something that is not an integer, like a decimal number or text? Our current program is designed to work with integers (int), and providing non-integer input will cause an error.

In this step, we will modify our program to take input from the user and handle cases where the input is not a valid integer. We will use the Scanner class, which we briefly saw in the "Your First Java Lab", to read user input.

  1. Open the EvenCheck.java file in the WebIDE editor.

  2. Replace the entire content of the file with the following code:

    import java.util.Scanner;
    import java.util.InputMismatchException;
    
    public class EvenCheck {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter an integer: ");
    
            try {
                int number = scanner.nextInt(); // Read integer input from the user
    
                // Use the modulo operator to check for a remainder when divided by 2
                if (number % 2 == 0) {
                    System.out.println(number + " is an even number.");
                } else {
                    System.out.println(number + " is an odd number.");
                }
    
            } catch (InputMismatchException e) {
                System.out.println("Invalid input. Please enter an integer.");
            } finally {
                scanner.close(); // Close the scanner
            }
        }
    }

    Let's look at the changes:

    • import java.util.Scanner;: Imports the Scanner class to read input.
    • import java.util.InputMismatchException;: Imports the exception class that is thrown when the input does not match the expected type.
    • Scanner scanner = new Scanner(System.in);: Creates a Scanner object to read input from the console.
    • System.out.print("Enter an integer: ");: Prompts the user to enter a number.
    • try { ... } catch (InputMismatchException e) { ... }: This is a try-catch block, which is used for error handling. The code inside the try block is executed. If an InputMismatchException occurs (meaning the input is not an integer), the code inside the catch block is executed.
    • int number = scanner.nextInt();: This line attempts to read an integer from the user input. If the user enters something that cannot be interpreted as an integer, an InputMismatchException is thrown.
    • System.out.println("Invalid input. Please enter an integer.");: This message is printed if an InputMismatchException is caught.
    • finally { scanner.close(); }: The code inside the finally block is always executed, regardless of whether an exception occurred or not. It's used here to close the Scanner resource.
  3. Save the file.

  4. Compile the modified program in the Terminal:

    javac EvenCheck.java
  5. Run the program:

    java EvenCheck
  6. When prompted, enter an integer (e.g., 15) and press Enter. The program should correctly identify if it's even or odd.

    Enter an integer: 15
    15 is an odd number.
  7. Run the program again:

    java EvenCheck
  8. This time, when prompted, enter a non-integer value (e.g., hello or 3.14) and press Enter. The program should now handle the invalid input gracefully.

    Enter an integer: hello
    Invalid input. Please enter an integer.

By adding the try-catch block, our program is now more robust and can handle cases where the user provides input that is not in the expected format. This is an important aspect of writing user-friendly programs.

Summary

In this lab, we learned how to check if a number is even in Java using the modulo operator (%). We discovered that an even number has a remainder of 0 when divided by 2. We implemented a simple Java program using an if-else statement to perform this check and print whether a given integer is even or odd.

We further explored testing the even check with both positive and negative integer inputs to ensure the modulo operator behaves as expected for different signs. Finally, we considered how to handle non-integer inputs, understanding that the modulo operator is typically used with integer types and discussing potential approaches for validating input types or handling exceptions in a more robust application.