Skip to content

Convert boolean to int in Java

To convert a boolean value to an integer in Java, you can use a conditional (ternary) operator. This is the standard and most concise approach.

Here's an example of how you can use the conditional operator to convert a boolean to an integer:


java
boolean b = true;
int i = b ? 1 : 0;

This will assign the value 1 to i if b is true, and 0 if b is false.

If you are working with a Boolean object instead of a primitive boolean, you can use Integer.valueOf() with a conditional expression:


java
Boolean bObj = true;
int i = Integer.valueOf(bObj ? 1 : 0);

This will also assign the value 1 to i if bObj is true, and 0 if bObj is false.

Both approaches will give you the same result, but the conditional operator is usually more concise and easier to read.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.