**Get started with Spring 5 and Spring Boot 2, through the ***Learn Spring* course:

*Learn Spring*course:

Last modified: August 4, 2022

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.**

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));
```

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.**

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

**An odd number OR 1 will always result in the**

```
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));
```

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

```
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));
```

**Bitwise XOR is the**

**An even number XOR 1 always**

```
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));
```

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));
```

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.

2 Comments

Oldest

Follow the Java Category

Follow the Java category to get regular info about the new articles and tutorials we publish here.