To Check Odd or Even In Java

Yuvaraj
2 min readAug 9, 2024

--

Basic Java Program

In mathematics, odd and even are terms used to classify integers based on their divisibility by 2.

Even Numbers

Definition: An even number is any integer that is divisible by 2 without leaving a remainder.

Characteristics:

  • When divided by 2, the result is an integer.
  • The remainder of the division by 2 is 0.
  • Even numbers end in 0, 2, 4, 6, or 8 in decimal notation.

Examples:

  • 2: 2 ÷ 2 = 1, remainder = 0
  • 4: 4 ÷ 2 = 2, remainder = 0
  • 10: 10 ÷ 2 = 5, remainder = 0

General Form: An even number can be expressed as 2k, where k is an integer.

Odd Numbers

Definition: An odd number is any integer that is not divisible by 2 without leaving a remainder.

Characteristics:

  • When divided by 2, the result is not an integer (there is a remainder of 1).
  • Odd numbers end in 1, 3, 5, 7, or 9 in decimal notation.

Examples:

  • 1: 1 ÷ 2 = 0, remainder = 1
  • 3: 3 ÷ 2 = 1, remainder = 1
  • 7: 7 ÷ 2 = 3, remainder = 1

General Form: An odd number can be expressed as 2k + 1, where k is an integer.

Key Points

  • Divisibility by 2: The main distinction between odd and even numbers is whether or not they are divisible by 2.
  • Even Numbers: Always have a remainder of 0 when divided by 2.
  • Odd Numbers: Always have a remainder of 1 when divided by 2.

These properties are fundamental in number theory and are widely used in various applications in mathematics and computer science.

import java.util.Scanner;

public class OddEvenChecker {

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

// Input a number from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();

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

// Close the Scanner to release resources
scanner.close();
}
}

Explanation

  1. Input:
  • The program prompts the user to enter a number using Scanner.

2. Check Even or Odd:

  • number % 2 == 0: This condition checks if the number is divisible by 2 without leaving a remainder.
  • If true, the number is even, so the program prints that the number is even.
  • If false, the number is odd, so the program prints that the number is odd.

3. Output:

  • The program displays whether the entered number is even or odd based on the result of the modulo operation.

How It Works:

  • Even Number: When a number is divided by 2, if the remainder is 0 (number % 2 == 0), it means the number is evenly divisible by 2 and hence even.
  • Odd Number: If the remainder is not 0 (number % 2 != 0), the number is not divisible by 2 evenly and is therefore odd.

This method is straightforward and efficient for determining if a number is odd or even.

--

--

Yuvaraj
Yuvaraj

No responses yet