Java Program to Check Even/Odd Number
Welcome to the world of computer programming! In this article, we will discuss how to write a program in Java to accept a number and check whether a number is Even or Odd. We will look at the different methods and techniques that can be used to accomplish this task.
#Method 1: Using if…else statement
import java.util.Scanner;
public class EvenOdd
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n;
System.out.print("Enter an integer: ");
n = in.nextInt();
if (n % 2 == 0)
{
System.out.println(n + " is even.");
}
else
{
System.out.println(n + " is odd.");
}
}
}
Output:
Enter an integer: 512
512 is even.
Explain:
The in
class is used to read input from the user.
The nextInt
method of the in
class is used to read an integer from the user.
The %
operator is used to calculate the remainder when the n
is divided by 2. If the remainder is 0, the number is even. If the remainder is 1, the number is odd.
The if
statement is used to check if the number is even or odd and print the result.
#Method 2: Using the ternary operator
import java.util.Scanner;
public class EvenOdd
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n;
String result;
System.out.print("Enter a number: ");
n = in.nextInt();
result = (n % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is " + result);
}
}
Output:
Enter a number: 90147
The number is Odd
Explain:
In this program, we first import the Scanner
class and create an Scanner
object in
to read input from the user. Then we prompt the user to enter a number and store it in the n
variable.
Next, we use the ternary operator ? :
to check if the number is even or odd. If n
% 2 == 0, it means that the number is divisible by 2, and hence even, the result is set to "Even"
. If not, the result is set to "Odd"
.
Finally, we print the result by concatenating the string "The number is "
with the result
variable.
Conclusion
In conclusion, this Java program has demonstrated a useful approach to determining whether a given number is even or odd. By making use of the modulo operator, the program was able to determine the remainder of the number when divided by two and then used an if-else statement to determine whether the number was even or odd. As a result, this program provides an effective and efficient means of checking whether a number is even or odd.