In the Following example OddorEvenNumbers use mod operator to check if the number is even or odd. If the number divided by 2 and the reminder is 0 then number is even, otherwise the number is odd.
Here is the java code for the program OddorEvenNumbers :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class OddorEvenNumbers {
public static void main(String[] args) {
int no = 0;
System.out.print("Please enter a Number :");
try
{
BufferedReader Buffer= new BufferedReader(new InputStreamReader(System.in));
no = Integer.parseInt(Buffer.readLine());
if(no%2 == 0)
System.out.println(no + " is Even Number.");
else
System.out.println(no + " is Odd Number.");
}
catch(Exception e)
{
System.out.println("Input Error : "+e);
}
}
}
Suppose, the value entered is say 217. It is assigned to the integer variable no. Now, no is divided by 2 (% returns remainder). Since 10 will be divided by 2 completely and remainder comes out to be o. Hence, we get the message” Number is even” on the screen. When we enter a value say 217, this time we get remainder as 1 and it will display the message “Number is odd” on the screen.