Even and Odd number check Java Example
There are many way to find if a number is even or odd in Java but before moving into technical details on finding even and odd number in Java let's what is even and odd number in terms of Mathematics. Any number which is completely divisible by 2 is called even number while number which is not completely divisible by 2 is called odd number. If you think in terms of remainder than in case of even number, remainder is zero while in case of odd number remainder will be 1. zero is considered as even number in maths. We can use this property to find whether a number is even or odd in Java. Java has a remainder operator also called modules operation denoted by % which does exactly same. it return remainder as a result of division. here is an Java sample program of finding even and odd number using remainder and bitwise AND operator in Java.
Java program to find even and odd number in Java
As I said there are multiple ways to check if a number is even or not in Java and if a number is not even than it certainly be odd. Like you can use division operator in a loop and starting from 1 keep multiplying it by 2 until you cross the number, if number matches than its an even number otherwise its an odd number.Another way of finding even and odd number is by using bit wise operator in Java. In binary format even number has there LSB always zero while odd number has there LSB as 1 by using this information and bit-wise & operator we can find if a number is even or odd in Java. By the way in this example we will see two ways to check if number is odd or even, first by using remainder operator and second by using bitwise AND operator in Java.
That’s all on How to check if a number is even or odd in Java. Surely there are many other ways to check if a number is odd or even and you can certainly find more innovative and creative way of doing it but this is something very useful to know. Some time interviewer twist it little bit and said how do you check if number is even or odd without using arithmetic operator and remainder operator, well bit-wise AND is your option which is also fastest method to check even and odd in Java.