Java Program to Determine if a Number is Odd or Even
This Java program checks whether a given number is odd or even. Below is the complete code with an explanation of each part of the program structure and documentation.
Program Code
// Importing the Scanner class for user input
import java.util.Scanner;
/**
* This class contains a method to determine if a number is odd or even.
*/
public class OddEvenChecker {
/**
* The main method is the entry point of the program.
* @param args Command line arguments (not used in this program)
*/
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.println("Enter a number: ");
int number = scanner.nextInt();
// Check if the number is odd or even and display the result
if (isEven(number)) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}
// Close the scanner object to prevent resource leak
scanner.close();
}
/**
* This method checks if a given number is even.
* @param num The number to be checked
* @return true if the number is even, false otherwise
*/
public static boolean isEven(int num) {
// A number is even if it is divisible by 2
return num % 2 == 0;
}
}
Explanation of the Program
Let’s break down the program into its main components:
- Importing the Scanner class: We import
java.util.Scanner
to use the Scanner class for reading input from the user. - Class Definition: The
OddEvenChecker
class contains the main method and a helper methodisEven
. - Main Method: The
main
method is the entry point of the program. It prompts the user to enter a number, reads the input, checks if the number is even or odd using theisEven
method, and then displays the result. - isEven Method: This method takes an integer as a parameter and returns
true
if the number is even (i.e., divisible by 2) andfalse
otherwise. - Closing the Scanner: We close the Scanner object after using it to prevent resource leaks.