Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to check a given number is even or odd.

Java Code Example — Conditional Programs

ADVERTISEMENT

Java Program to check a given number is even or odd.

Objective

Write a Java program to determine whether a given integer is even or odd.

Algorithm / Approach

  1. Read a single integer from the user.
  2. Use the modulo operator to compute x % 2.
  3. If the remainder is exactly equal to 0, print that the number is EVEN.
  4. Otherwise, print that the number is ODD.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter a Num.: ");
  int x = s.nextInt();
  if(x%2==0){
   System.out.print(x+" IS AN EVEN");
  }
  else {
   System.out.print(x+" IS AN ODD");
  }
 }
}

Expected Output

Enter a Num.: 20
20 IS AN EVEN

Explanation of the Program

  • The modulo operator % returns the remainder of a division operation.
  • Dividing any even number by 2 leaves a remainder of 0.
  • Dividing any odd number by 2 leaves a remainder of 1.
  • The == operator is used to compare the remainder with 0.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Using the assignment operator = instead of the equality operator == in the if-condition.
  • Using division / instead of modulo %.
ADVERTISEMENT