In this article, we will write two java programs to check whether a number is even or odd. If a number is perfectly divisible by 2 (number % 2 ==0
) then the number is called even number, else the number is called odd number.
Perfectly divisible by 2 means that when the number is divided by 2 the remainder is zero. To check for remainder, we use modulus operator in java.
Example 1: Program to check if the number entered by user is even or odd
In this program, we have an int variable num
. We are using Scanner class to get the number entered by the user.
Once the entered number is stored in the variable num, we are using if..else statement to check if the number is perfectly divisible by 2 or not. Based on the outcome, it is executing if block (if condition true) or else block (if condition is false).
import java.util.Scanner; public class JavaExample { public static void main(String args[]) { int num; System.out.print("Enter an Integer number: "); //The input provided by user is stored in num Scanner input = new Scanner(System.in); num = input.nextInt(); // If number is divisible by 2 then it's an even number //else it is an odd number if ( num % 2 == 0 ) System.out.println(num+" is an even number."); else System.out.println(num+" is an odd number."); } }
Output 1:
Output 2:
Example 2: Program to check even odd number using ternary operator
A ternary operator is a one liner replacement of an if-else statement. In this program, we are using the same logic that we have seen above, however instead of using if..else, we are using a ternary operator here.
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter any number: "); int num = scan.nextInt(); //checking if else using ternary operator //ternary operator syntax: condition ? expression1 : expression2 // if condition is true, expression1 executes else expression2 String evenOrOdd = (num % 2 == 0) ? "even number" : "odd number"; System.out.println(num + " is an " + evenOrOdd); } }
Output 1: When user enters 32 number.
Enter any number: 32 32 is an even number
Output 2: When user enters 13 number.
Enter any number: 13 13 is an odd number
kaushik says
there are errors in the program its saying that FILE DOES NOT CONTAIN CLASS SCANNER :\
Mohammad Yahiya Khan says
Bro check your compiler or write import java.util.*; instead of Scanner then it will get compiled.
arul says
if i run any programs like usergetinputs it shows the following error
” class java.util.Scanner not found in import.”
please help me to correct this error thank you.
Sultan says
import package java.util.Scanner;
Then it will not show any error..!
Shubh Gupta says
Pls type import java.util.*; on the top of the program above the public class
Vraj says
Use import java.util.*;
This will 100% 😉 work
Rukhsaar says
I tried this and there were no errors whatsoever .