Convert boolean to int in Java
To convert a boolean value to an integer in Java, you can use the intValue()
method of the java.lang.Boolean
class, or you can use a conditional operator.
Here's an example of how you can use the intValue()
method to convert a boolean to an integer:
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
.
Alternatively, you can use the intValue()
method of the Boolean
class to convert a boolean to an integer:
boolean b = true;
int i = Boolean.valueOf(b).intValue();
This will also assign the value 1 to i
if b
is true
, and 0 if b
is false
.
Both of these methods will give you the same result, but the conditional operator is usually more concise and easier to read.