How to create a method to return 1 or 0 without using conditions?
We can use the xor operator here. Xor is "exclusive or" and returns a 0 when there are two or zero 1's and returns 1 if there's exactly one 1. It does this on every bit of the integer.
So for example, the binary 1001 ^ 1000 = 0001 as the first bit has two 1's, so 0, the next two have no 1's, so zero, and the final bit only has one 1, outputting a 1.
public int testMethod(int value){
return value ^ 1;
}
public int testMethod(int value) {
return 1 - (value % 2); // or 1 - (value & 1)
}
This could use to switch between any value and 0, EG 3:
public int testMethod3(int value) {
return 3 - (value % 4);
}
And just to cover the return 0
at the end of the sample in the question:
private static final int[] VALUES = { 1, 0 };
public int testMethod(int value) {
try {
return VALUES[value];
} catch (ArrayIndexOutOfBoundsException ex) {
return 0;
}
}
If you are given only 0 and 1 then this could be simpler:
return 1 - value;