Convert a boolean to an int in Java

In this post, we 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. Ternary Operator

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

 

 

2. Using Boolean.compareTo()

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

 

 

3. Java 7

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

 

 

4. Apache Commons Lang

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

 

 

5. String.length()

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

 

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

 

 

6. String.indexOf()

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

 

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

 

 

7. Boolean.hashCode()

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

 

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

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz