## 1.概述

As we know, the parity of a number is determined by the remainder of its division by 2. Even numbers generate a remainder of 0, while odd numbers generate a remainder of 1.

In this tutorial, we’ll see multiple ways to check whether a number is even or odd in Java.

## 2.师的方法

The arithmetic operator which returns the division remainder is the modulus operator %.

The easiest way we can verify if a number is even or odd is by making the mathematical operation of dividing the number by 2 and checking the remainder:

``````boolean isEven(int x) {
return x % 2 == 0;
}

boolean isOdd(int x) {
return x % 2 != 0;
}``````

Let’s write a couple of tests to confirm the behavior of our methods:

``````assertEquals(true, isEven(2));
assertEquals(true, isOdd(3));``````

## 3.位操作法

There are multiple bitwise operations that we can do on a number to determine if it’s even or odd.

The bitwise operations are more performant than the other methods to determine the parity of a number.

### 3.1 位法OR (|)

An even number OR 1 will always increment the number by 1.

An odd number OR 1 will always result in the same number:

``````boolean isOrEven(int x) {
return (x | 1) > x;
}

boolean isOrOdd(int x) {
return (x | 1) == x;
}``````

Let’s demonstrate the behavior of our code with some tests:

``````assertEquals(true, isOrEven(4));
assertEquals(true, isOrOdd(5));``````

### 3.2. 位法AND (&)

An even number AND 1 always results in a 0. On the other hand, an odd number AND 1 results in a 1:

``````boolean isAndEven(int x) {
return (x & 1) == 0;
}

boolean isAndOdd(int x) {
return (x & 1) == 1;
}``````

We’ll confirm this behavior with a small test:

``````assertEquals(true, isAndEven(6));
assertEquals(true, isAndOdd(7));``````

### 3.3 位法XOR（^）。

Bitwise XOR is the optimal solution to check the parity of a number.

An even number XOR 1 always increases the number by 1, while an odd number XOR 1 always decreases it by 1:

``````boolean isXorEven(int x) {
return (x ^ 1) > x;
}

boolean isXorOdd(int x) {
return (x ^ 1) < x;
}``````

Let’s write some small tests to check our code:

``````assertEquals(true, isXorEven(8));
assertEquals(true, isXorOdd(9));``````

## 4.最小有效位（LSB）

The last method that we are presenting is reading the least significant bit of the number.

An even number’s least significant bit is always 0, while that of an odd number is always 1:

``````boolean isLsbEven(int x) {
return Integer.toBinaryString(x).endsWith("0");
}

boolean isLsbOdd(int x) {
return Integer.toBinaryString(x).endsWith("1");
}``````

We’ll demonstrate this behavior with a few lines of code:

``````assertEquals(true, isLsbEven(10));
assertEquals(true, isLsbOdd(11));``````

## 5.总结

In this article, we’ve learned multiple ways to check the parity of a number, i.e., whether it’s even or odd. We saw that the optimal solution for checking the parity is the bitwise XOR operation.

As always, the source code for the examples is available over on GitHub.