Home
Map
Convert boolean to intConvert a boolean to an int with a ternary expression. A boolean cannot be cast to an int.
Java
This page was last reviewed on Jun 9, 2021.
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.
Cast
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.
Detail We test 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
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.
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.
C#VB.NETPythonGoJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 9, 2021 (edit).
Home
Changes
© 2007-2023 Sam Allen.