Check the number is even or odd

This Java code example demonstrates how to determine whether a given integer is even or odd. The program prompts the user to enter a value, checks if the number is even or odd using the modulus operator, and then prints the result.

Code Example

import java.util.Scanner;

class EvenOrOdd {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int x;

        System.out.print("Enter a value for x: ");
        x = reader.nextInt();
        reader.close();

        if (x % 2 == 0) {
            System.out.print("Number " + x + " is even");
        } else {
            System.out.print("Number " + x + " is odd");
        }
    }
}

Code Explanation

Class Definition

class EvenOrOdd

The class EvenOrOdd contains the main method to execute the program.

class EvenOrOdd {
    // class contents
}

Main Method

public static void main(String[] args)

The main method executes the program and contains the logic for determining if a number is even or odd.

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    int x;

    System.out.print("Enter a value for x: ");
    x = reader.nextInt();
    reader.close();

    if (x % 2 == 0) {
        System.out.print("Number " + x + " is even");
    } else {
        System.out.print("Number " + x + " is odd");
    }
}

Creating Scanner Object

  • Scanner reader = new Scanner(System.in); creates a Scanner object to read input from the user.

Variable Declaration

  • int x; declares a variable to store the input value.

Prompting for User Input

  • System.out.print("Enter a value for x: "); prompts the user to enter a value.
  • x = reader.nextInt(); reads the integer input and assigns it to the variable x.
  • reader.close(); closes the Scanner object to free up resources.

Conditional Statement to Check Even or Odd

  • if (x % 2 == 0) { checks if the number is even by using the modulus operator % to see if there is no remainder when x is divided by 2.
  • System.out.print("Number " + x + " is even"); prints that the number is even if the condition is true.
  • } else { handles the case where the number is odd.
  • System.out.print("Number " + x + " is odd"); prints that the number is odd if the condition is false.