Java Convert boolean to intConvert a boolean to an int with a ternary expression. A boolean cannot be cast to an int.
dot net perls
Convert boolean, 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.
A problem. 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.
Ternary Operator
Example method. 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.
Main We test booleanToInt in the main method. When the boolean is false, we print 0 and when it is true we print 1.
Java program that converts boolean to int
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
Error, cast boolean. 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.
Java program that causes error, casts boolean
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)
Performance notes. The booleanToInt method requires a branch in its implementation. This is not as fast as simply using 0 and 1 to represent truth.
Tip To achieve the best performance, avoiding conversions and branches is often the best option.
What we accomplished. 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.
© 2007-2021 sam allen. see site info on the changelog