This post will discuss how to convert a boolean to an int in Java. The convention should be such that true is 1, and false is 0.

1. Using Ternary Operator

The most common, efficient, and most readable way is to use the ternary operator. This approach works for both primitive-type boolean and Boolean class.

2. Using Boolean.compareTo() method

We can use Boolean.compareTo() to compare a Boolean instance with another. This approach won’t work on primitive-type boolean.

3. Using Boolean.compare() method

Java 7 introduced a new utility method Boolean.compare() that compares two boolean values. This internally uses a ternary operator and works with both primitive-type boolean and Boolean class.

4. Using Apache Commons Lang

We can also use Apache Commons Lang BooleanUtils.toInteger() that returns an integer equivalent of the specified boolean.

5. Using String.length() method

This approach takes advantage of the fact that the difference between the lengths of the string representation of the boolean values is 1.

 
For primitive-type boolean, we can do something like:

6. Using String.indexOf() method

Another indirect approach involves the use of String.indexOf(), as shown below:

 
For primitive-type boolean, we can do something like:

7. Using Boolean.hashCode() method

Finally, let’s involve some low-level bit manipulation hacks.

That’s all about converting a boolean to an int in Java.

 
Reference: https://stackoverflow.com/questions/3793650/convert-boolean-to-int-in-java