Friday 26 November 2021

Java: Check whether number is even or odd using bitwise operator

Using bitwise and (&) operator, you can check whether a number is even or odd. 

 


Perform bitwise and operation with 1, if the result is 1, then it is odd number, if the result is 0 then it is even number.

 


 

Find the below working application.

 

EvenOddCheckWithBitwiseAnd.java

package com.sample.app.numbers;

public class EvenOddCheckWithBitwiseAnd {

	public static void main(String args[]) {
		int a = 12;
		int b = 13;

		if ((a & 1) == 0) {
			System.out.println(a + " is even number");
		} else {
			System.out.println(a + " is odd number");
		}

		if ((b & 1) == 0) {
			System.out.println(b + " is even number");
		} else {
			System.out.println(b + " is odd number");
		}
	}

}

 

Output

12 is even number
13 is odd number



You may like

No comments:

Post a Comment