user3122903 user3122903 - 2 years ago 74
Java Question

Determine whether number is odd or even without using conditional code

How to find whether a number is odd or even, without using

condition or ternary operators in Java?

This question is given by my teacher. He also give me a hint that it is possible by using a bitwise operator.

Answer Source

There are few ways to not use if and get behavior that will be same as if if was used, like ternary operator condition ? valueIfTrue : valueIfFalse or switch/case.

But to be tricky you can also use arrays and try to figure some transformation of our value to proper array index. In this case your code could look like

int number = 13;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);


13 is odd

You can change number % 2 with number & 1 to use suggestion of your teacher. Explanation of how it works can be found here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download