Convert a boolean to an int in Java
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.
|
1 2 3 |
public static int boolToInt(Boolean b) { return b ? 1 : 0; } |
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.
|
1 2 3 |
public static int boolToInt(Boolean b) { return b.compareTo(false); } |
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.
|
1 2 3 |
public static int boolToInt(Boolean b) { return Boolean.compare(b, false); } |
4. Using Apache Commons Lang
We can also use Apache Commons Lang BooleanUtils.toInteger() that returns an integer equivalent of the specified boolean.
|
1 2 3 |
public static int boolToInt(Boolean b) { return BooleanUtils.toInteger(b); } |
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.
|
1 2 3 |
public static int boolToInt(Boolean b) { return 5 - b.toString().length(); } |
For primitive-type boolean, we can do something like:
|
1 2 3 |
public static int boolToInt(boolean b) { return 5 - (b + "").length(); } |
6. Using String.indexOf() method
Another indirect approach involves the use of String.indexOf(), as shown below:
|
1 2 3 |
public static int boolToInt(Boolean b) { return -("false".indexOf(b.toString())); } |
For primitive-type boolean, we can do something like:
|
1 2 3 |
public static int boolToInt(boolean b) { return -("false".indexOf(b + "")); } |
7. Using Boolean.hashCode() method
Finally, let’s involve some low-level bit manipulation hacks.
|
1 2 3 |
public static int boolToInt(Boolean b) { return 1 & (Boolean.hashCode(b) >> 1); } |
That’s all about converting a boolean to an int in Java.
Reference: https://stackoverflow.com/questions/3793650/convert-boolean-to-int-in-java
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)