# Java Program to Check Odd or Even Numbers

To find whether a number is odd or even, we will check whether given number is completely divisible by 2 or not. Every even number can be represented as (2*N) whereas every odd number can be represented as (2*N + 1).

How to check whether a number is odd or even ?
• If a number is divisible by 2, then it is an even number.
• If a number is not divisible by 2, then it is an odd number.
For Example :
8%2 = 0 (8 is even number)
9%2 = 1 (9 is odd number)

## Java program to check whether a number is Odd or Even

In this program, we first take an integer as input from user and store it in a variable "num". Then using an if-else statement we check whether "num" is divisible by 2 or not. If "num" is completely divisible by 2 then it is an even number otherwise odd.

```package com.tcc.java.programs;

import java.util.Scanner;
/**
* Java Program to check whether a number is odd or even
*/
public class EvenOddNumberCheck {
public static void main(String[] args) {
int num;
Scanner scanner;
// Take an integer from user
scanner = new Scanner(System.in);
System.out.println("Enter an Integer");
num = scanner.nextInt();

/*
* Using if-else statement check whether num is divisible
* by 2 or not.
*/
if (num % 2 == 0) {
// num is even
System.out.println(num + " is Even Number");
} else {
// num is odd
System.out.println(num + " is Odd Number");
}
}
}
```
Output
```Enter an Integer
5
5 is Odd Number
```
```Enter an Integer
4
4 is Even Number
```

## Java program to check Odd or Even numbers using function

This program is similar to above program except it uses a method "isEven" which takes an integer as argument and returns true if passed number is even otherwise odd. The advantage of writing a separate function to check odd and even number is that we can call this function from several different places eliminating redundancy.

```package com.tcc.java.programs;

import java.util.Scanner;

/**
* Java Program to check whether a number is odd or
* even using a function
*/

public class EvenOddNumberCheckFunction {

public static void main(String[] args) {
int num;
Scanner scanner;
// Take an integer from user
scanner = new Scanner(System.in);
System.out.println("Enter an Integer");
num = scanner.nextInt();

/*
* Calling isEven method to check whether num is even or odd.
*/
if (isEven(num)) {
// num is even
System.out.println(num + " is Even Number");
} else {
// num is odd
System.out.println(num + " is Odd Number");
}
}

/**
* Returns 1 if num is even else return 0.
*/
public static boolean isEven(int num) {
if (num % 2 == 0)
return true;
else
return false;
}
}
```
Output
```Enter an Integer
9
9 is Odd Number
```
```Enter an Integer
8
8 is Even Number
```

Recommended Posts