In Java programming, checking whether a number is even or odd is a fundamental task.
In this tutorial, we’ll show you how to write a simple Java program to determine if a given number is even or odd.
To check if a number is even or odd, we use the modulo operator (%).
The modulo operator gives us the remainder when one number is divided by another.
If the remainder is 0, then the number is even; otherwise, it’s odd.
Here’s the Java program to check whether a number is even or odd:
import java.util.Scanner; public class EvenOrOdd { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); if (number % 2 == 0) { System.out.println(number + " is even"); } else { System.out.println(number + " is odd"); } scanner.close(); } }
Let’s break down the code:
- We first import the Scanner class to get input from the user.
- We create a new Scanner object and prompt the user to enter a number.
- We read the input from the user and store it in the variable number.
- We use the if statement to check if the number is even or odd.
- If the number is even, we print a message saying so. Otherwise, we print a message saying the number is odd.
- We close the scanner to free up resources.
To test the program, compile and run it. When prompted, enter a number and press enter.
The program will then tell you if the number is even or odd.
In conclusion, checking whether a number is even or odd is a simple task in Java programming.
We use the modulo operator to determine if a number is even or odd, and then we print out the result.
The program we wrote above is a basic example of how to do this, but it can be modified to suit more complex requirements.