Detect even/odd number with the modulus operator.
public class Main {
public static void main(String[] argv) {
int x = 5;
if (x % 2 == 0) {
System.out.println("even");
}
if (x % 2 != 0) {
System.out.println("odd");
}
// ... or binary AND operator...
if ((x & 1) == 0) {
System.out.println("even");
}
if ((x & 1) != 0) {
System.out.println("odd");
}
}
}
Related examples in the same category