Home
Java
Convert boolean to int
Updated Jun 9, 2021
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.
Cast
Ternary
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 9, 2021 (edit).
Home
Changes
© 2007-2025 Sam Allen