How to Check If a Number Is Odd in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to determine if a number is odd or even in Java using the modulo operator. We will explore the concept of the modulo operator and how its result when dividing by 2 can distinguish between odd and even numbers.

Through hands-on steps, you will apply the modulo operator to check for odd numbers, verify the logic with various number types, and combine checks for both even and odd numbers, gaining practical experience in conditional logic in Java.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) 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") subgraph Lab Skills java/data_types -.-> lab-559967{{"How to Check If a Number Is Odd in Java"}} java/operators -.-> lab-559967{{"How to Check If a Number Is Odd in Java"}} java/if_else -.-> lab-559967{{"How to Check If a Number Is Odd in Java"}} java/user_input -.-> lab-559967{{"How to Check If a Number Is Odd in Java"}} end

Apply Modulo Operator for Odd Check

In this step, we will learn how to determine if a number is odd or even using the modulo operator in Java. 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.

A number is even if it is perfectly divisible by 2, meaning the remainder when divided by 2 is 0. A number is odd if the remainder when divided by 2 is 1.

Let's create a new Java program to check if a number is odd.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

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

    import java.util.Scanner;
    
    public class HelloJava {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter an integer: ");
            int number = scanner.nextInt();
    
            // Check if the number is odd using the modulo operator
            if (number % 2 != 0) {
                System.out.println(number + " is an odd number.");
            } else {
                System.out.println(number + " is an even number.");
            }
    
            scanner.close();
        }
    }

    Let's look at the new parts of the code:

    • int number = scanner.nextInt();: This line reads an integer value entered by the user and stores it in a variable named number.
    • if (number % 2 != 0): This is an if statement, which allows our program to make decisions. It checks if the remainder of number divided by 2 is not equal to 0. The != symbol means "not equal to".
    • System.out.println(number + " is an odd number.");: This line is executed if the condition in the if statement is true (the number is odd).
    • else: This keyword introduces the block of code to be executed if the condition in the if statement is false (the number is even).
    • System.out.println(number + " is an even number.");: This line is executed if the number is even.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java

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

  5. Run the compiled program:

    java HelloJava
  6. The program will prompt you to enter an integer. Enter a number (e.g., 7) and press Enter. The program should tell you if the number is odd or even.

    Enter an integer: 7
    7 is an odd number.

    Run the program again and enter an even number (e.g., 10).

    Enter an integer: 10
    10 is an even number.

You have successfully used the modulo operator and an if-else statement to check if a number is odd or even. This is a fundamental concept in programming for controlling the flow of your program based on conditions.

Verify with Various Number Types

In the previous step, we successfully checked if an integer is odd or even. Now, let's explore how the modulo operator behaves with different types of numbers, specifically focusing on negative integers.

The concept of odd and even numbers typically applies to integers. However, it's important to understand how the modulo operator works with negative numbers in Java, as it might behave differently than you expect based on mathematical definitions.

In Java, the result of the modulo operation (a % b) has the same sign as the dividend (a).

Let's modify our program to test with negative numbers.

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

  2. The current code already reads an integer. We can use the same code and simply input negative numbers when running the program.

    import java.util.Scanner;
    
    public class HelloJava {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter an integer: ");
            int number = scanner.nextInt();
    
            // Check if the number is odd using the modulo operator
            if (number % 2 != 0) {
                System.out.println(number + " is an odd number.");
            } else {
                System.out.println(number + " is an even number.");
            }
    
            scanner.close();
        }
    }
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program again to make sure you have the latest version:

    javac HelloJava.java
  5. Run the program:

    java HelloJava
  6. When prompted, enter a negative odd number (e.g., -7) and observe the output.

    Enter an integer: -7
    -7 is an odd number.

    The output correctly identifies -7 as odd because -7 divided by 2 is -3 with a remainder of -1. Since -1 is not equal to 0, the if condition number % 2 != 0 is true.

  7. Run the program again and enter a negative even number (e.g., -10).

    Enter an integer: -10
    -10 is an even number.

    The output correctly identifies -10 as even because -10 divided by 2 is -5 with a remainder of 0. The if condition number % 2 != 0 is false, and the else block is executed.

This demonstrates that our current logic for checking odd/even numbers using the modulo operator works correctly for both positive and negative integers in Java. The key is that the remainder of an odd number divided by 2 will always be non-zero (either 1 or -1), while the remainder of an even number divided by 2 will always be 0.

Combine Even and Odd Checks

In the previous steps, we learned how to use the modulo operator to check if a number is odd or even. Our current program already handles both cases using an if-else statement.

In this step, we will review the code and ensure we understand how the if-else structure effectively combines the checks for both even and odd numbers.

Recall the code we used in the previous step:

import java.util.Scanner;

public class HelloJava {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        int number = scanner.nextInt();

        // Check if the number is odd using the modulo operator
        if (number % 2 != 0) {
            System.out.println(number + " is an odd number.");
        } else {
            System.out.println(number + " is an even number.");
        }

        scanner.close();
    }
}

Let's break down the logic again:

  • The condition number % 2 != 0 checks if the remainder when number is divided by 2 is not equal to 0.
  • If this condition is true, it means the number is odd, and the code inside the if block is executed: System.out.println(number + " is an odd number.");.
  • If the condition number % 2 != 0 is false, it means the remainder is equal to 0. In this case, the number must be even, and the code inside the else block is executed: System.out.println(number + " is an even number.");.

This if-else structure is a very common way to handle two mutually exclusive possibilities (either a number is odd or it's even). We don't need a separate check for even numbers because if a number is not odd, it must be even (for integers).

To complete this step, simply ensure your HelloJava.java file contains the correct code as shown above.

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

  2. Verify that the code matches the example provided above, including the import, Scanner usage, the prompt, reading the integer, the if-else statement with the modulo check, and closing the scanner.

  3. Save the file if you made any changes (Ctrl+S or Cmd+S).

  4. Compile the program one last time to be sure:

    javac HelloJava.java
  5. Run the program and test it with both odd and even numbers (positive and negative) to confirm it works as expected.

    java HelloJava

    Example output for an odd number:

    Enter an integer: 9
    9 is an odd number.

    Example output for an even number:

    Enter an integer: -4
    -4 is an even number.

You have now successfully implemented and verified a Java program that uses the modulo operator and an if-else statement to determine if an integer is odd or even. This fundamental concept of conditional logic is crucial for building more complex programs.

Summary

In this lab, we learned how to determine if a number is odd or even in Java using the modulo operator (%). We discovered that a number is even if the remainder when divided by 2 is 0, and odd if the remainder is 1. We implemented this logic in a Java program that takes user input and prints whether the number is odd or even.

We also explored how to verify this check with various number types and how to combine the logic for both even and odd checks within a single program using an if-else statement. This hands-on experience provided a practical understanding of conditional statements and the modulo operator in Java for basic number property checks.