int
A Java boolean is true or false. But often when developing a program we want the integer 1 or 0 to represent truth. We must convert a boolean to an int
.
We cannot cast a boolean to an int
in Java. We must use an if
-statement, or a ternary, to convert. A separate method can be used to encapsulate and name this logic.
Here we introduce a method booleanToInt
. We use a ternary expression to convert the boolean to 1 or 0. If true, we return 1. If false, we return the value 0.
booleanToInt
in the main method. When the boolean is false, we print 0 and when it is true we print 1.public class Program { public static int booleanToInt(boolean value) { // Convert true to 1 and false to 0. return value ? 1 : 0; } public static void main(String[] args) { // Test our conversion method. boolean value = false; int number = booleanToInt(value); System.out.println(number); System.out.println(booleanToInt(true)); } }0 1
This program does not work. It does not compile. It attempts to cast a boolean to an int
. This is not possible in Java—it cannot be done.
public class Program { public static void main(String[] args) { // This does not compile. boolean value = true; int value2 = (int) value; } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot cast from boolean to int at Program.main(Program.java:6)
The booleanToInt
method requires a branch in its implementation. This is not as fast as simply using 0 and 1 to represent truth.
We found that there is no way to directly cast a boolean to an int
in Java. This causes an error. Instead we can use a ternary to evaluate and return an int
.