What is the most accepted way to convert a boolean
to an int
in Java?
-
8What integers would you think corresponded to `true` and `false` respectively? – Thorbjørn Ravn Andersen Sep 25 '10 at 12:08
-
6Some languages have implicit conversion from int to boolean. Java doesn't. However, the official implementation has SQL packages, and I believe these convert "false" to 0. – hpique Sep 25 '10 at 12:22
-
Generally, a boolean should be left as a boolean. This is the accepted practice in Java. – Peter Lawrey Sep 25 '10 at 16:39
-
4@Peter Lawrey Not if you want to interoperate with other systems that don't have boolean as a non-numeric data type. – hpique Sep 25 '10 at 16:45
-
@hgpc, in which can you know which values you need true and false to represent. These are usually byte values (though most of the examples here are int values) but can be '0' or '1' (48 and 49) or 'T' and 'F', 'Y' or 'N' and their ascii values. – Peter Lawrey Sep 25 '10 at 21:55
-
7@Peter Lawrey The question is not really about the value mapping. It's about how to do the conversion in the most clear, accepted way. – hpique Sep 26 '10 at 07:36
-
@hgpc, you cannot code a mapping, if you don't know what to map to. – Thorbjørn Ravn Andersen Sep 27 '10 at 10:27
-
9Technically, the Java compiler already defines a mapping. True and False are compiled to 1 and 0 respectively. – Antimony Jul 23 '12 at 05:15
-
I have answered on similar question [here](http://stackoverflow.com/questions/13806021/checking-the-boolean-result-of-an-int-type/39878780#39878780) – Tioma Oct 05 '16 at 16:02
-
1What's the use case for that question? – inetphantom Aug 08 '18 at 12:04
-
Why can't (int)[boolean_variable] be used my compiler shows an error – Super Coder May 18 '23 at 18:04
12 Answers
int myInt = myBoolean ? 1 : 0;
^^
PS : true = 1 and false = 0

- 27,881
- 12
- 83
- 120

- 9,021
- 1
- 23
- 33
-
63In the case where myBoolean stands for a boolean expression, using parenthesis is more readable. – rsp Sep 25 '10 at 12:33
-
44Yes, as in `(foo && (!bar || baz)) ? 1 : 0`. Obviously, if it's just an identifier, the parens aren't necessary or desirable. – Blrfl Sep 25 '10 at 12:58
-
nice trick with boolean! I was looking might some casting exist like (int) true = 1, but noting exist like this :P – mumair Oct 26 '15 at 06:32
-
1for beginners like me, `(boolean expression) ? 1 : 0;` would be more understandable. I think `my` prefix made it look like a variable. – dixhom Mar 01 '16 at 23:50
-
12@Blrfl in your example parentheses are a *must*, not a matter of readability. `foo && (!bar || baz) ? 1 : 0` would be a syntax error. (I know it's been 6 years) – Konrad Morawski Apr 26 '16 at 11:23
-
@KonradMorawski in what way does `foo && (!bar || baz) ? 1 : 0` cause a syntax error? `?:` has lower precedence than both `&&` and `||`. – royhowie Oct 14 '19 at 03:56
-
1
-
I put an edit that added examples of how to use it in the middle of a numerical expression. – Ankit Jul 17 '20 at 04:35
Using the ternary operator is the most simple, most efficient, and most readable way to do what you want. I encourage you to use this solution.
However, I can't resist to propose an alternative, contrived, inefficient, unreadable solution.
int boolToInt(Boolean b) {
return b.compareTo(false);
}
Hey, people like to vote for such cool answers !
Edit
By the way, I often saw conversions from a boolean to an int for the sole purpose of doing a comparison of the two values (generally, in implementations of compareTo
method). Boolean#compareTo
is the way to go in those specific cases.
Edit 2
Java 7 introduced a new utility function that works with primitive types directly, Boolean#compare
(Thanks shmosel)
int boolToInt(boolean b) {
return Boolean.compare(b, false);
}

- 10,842
- 3
- 33
- 47
-
2Will be inlined by modern JIT's, so not necessarily inefficient. Also it documents why the b.compareTo is being used so it is readable. – Thorbjørn Ravn Andersen Jul 03 '11 at 13:02
-
3It can be slow because we need to box the primitive value in an object. The ternary operator method works directly with primitive values without conversion, so I think it's more efficient. – barjak Jul 03 '11 at 18:38
-
81. You can use `Boolean.compare()` and avoid the autoboxing. 2. The documentation for `Boolean.compareTo()` does not say it will return 1, only "a positive value if this object represents true and the argument represents false". – shmosel Oct 14 '14 at 22:14
-
3I just did a test converting 1,000,000 random Boolean values and this method was consistently faster than that based on the ternary operator. It shaved off about 10ms. – Mapsy Oct 24 '14 at 13:14
-
5@AlexT. if you do microbenchmarks you should use a framework to ensure that you measure correctly. See http://openjdk.java.net/projects/code-tools/jmh/. – Thorbjørn Ravn Andersen Nov 21 '14 at 08:31
-
@ThorbjørnRavnAndersen What did your test conclude? I used a visitor pattern to emulate an if statement, and provided the objects involved with the visitor pattern were pre allocated, the ternary operator was consistently slower. I assume this had to do with branch prediction. – Mapsy Nov 29 '14 at 10:27
-
-
@AlexT. I did not conclude anything. Perhaps you could make your test available so we can reproduce it? – Thorbjørn Ravn Andersen May 16 '17 at 13:54
boolean b = ....;
int i = -("false".indexOf("" + b));

- 73,784
- 33
- 194
- 347
-
7@ThorbjørnRavnAndersen Yeah. Using one of the other, more efficient, methods posted that doesn't require that overhead. Unless you can explain how creating string objects to simply check the value of a boolean is in any way efficient. – arkon Jun 05 '13 at 16:17
-
9
-
5@ThorbjørnRavnAndersen Micro-optimization has nothing to do with it, since it's all a matter of context. If I'm calling a method 1000000+ times which uses this block, then I'm potentially creating 1000000+ extra objects that need to be GC'd. I'm not sure how demanding things are at your job, but my boss would pull me aside and give me a wtf lecture if I tried using something like this. – arkon Jun 05 '13 at 16:40
-
@b1naryatr0phy if you call a slow method a gazillion times your boss should lecture you on memoization instead. – Thorbjørn Ravn Andersen Jun 05 '13 at 17:00
-
13@ThorbjørnRavnAndersen I have no control over how my methods are used or how often they are called, which is entirely the point. You're sacrificing both performance and readability for absolutely no tangible benefit. – arkon Jun 05 '13 at 17:06
-
3@b1naryatr0phy So if I used `Boolean.toString(b)` instead of `"" + b` in order to avoid the string concatenation that would be ok with you? – Thorbjørn Ravn Andersen Jun 25 '13 at 12:46
-
9Its definitely creative but I cannot think of a single advantage to using this method. It's more verbose, and (I'm guessing) less efficient, but it sure is an interesting method. – Mike Baxter Jul 26 '13 at 13:18
-
4@kennytm: Brilliant hack... but tiny nit pick: If `b` is primitive `boolean`, I think you need to use: `5 - Boolean.toString(b).length` – kevinarpe Jan 02 '16 at 07:59
-
-
1I'm going to upvote if this is sarcasm, in which case it's hilarious. I just can't figure if it is – MuhsinFatih May 03 '20 at 07:35
-
Even though this code might be valid and technically correct, aside from being inefficient compared to other suggestions, it is hard to read and understand. I would not recommend using this. – user1438038 May 10 '21 at 09:33
import org.apache.commons.lang3.BooleanUtils;
boolean x = true;
int y= BooleanUtils.toInteger(x);

- 485
- 4
- 6
-
7FWIW, `BooleanUtils.toInteger` is implemented as just `return bool ? 1 : 0;`. – Solomon Ucko Feb 27 '20 at 03:18
-
8
-
@EricDuminil This can slightly increase readability in case of nested ( ? : ) or long one-liners. – Pat Lee Apr 28 '21 at 10:59
-
@EricDuminil IMO `xyz.stream().map(BooleanUtils::toInteger)` is much more readable than `xyz.stream().map(x -> x ? 1 : 0)` – bb1950328 Oct 13 '21 at 14:13
-
@bb1950328: Yes, it's more readable, but it doesn't have anything to do with Apache Commons, though. You could simply use the method defined in https://stackoverflow.com/a/3794521/6419007 instead. – Eric Duminil Oct 13 '21 at 15:09
If you use Apache Commons Lang (which I think a lot of projects use it), you can just use it like this:
int myInt = BooleanUtils.toInteger(boolean_expression);
toInteger
method returns 1 if boolean_expression
is true, 0 otherwise

- 719
- 12
- 31
-
4FWIW, `BooleanUtils.toInteger` is implemented as just `return bool ? 1 : 0;`. – Solomon Ucko Feb 27 '20 at 03:19
That depends on the situation. Often the most simple approach is the best because it is easy to understand:
if (something) {
otherThing = 1;
} else {
otherThing = 0;
}
or
int otherThing = something ? 1 : 0;
But sometimes it useful to use an Enum instead of a boolean flag. Let imagine there are synchronous and asynchronous processes:
Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());
In Java, enum can have additional attributes and methods:
public enum Process {
SYNCHRONOUS (0),
ASYNCHRONOUS (1);
private int code;
private Process (int code) {
this.code = code;
}
public int getCode() {
return code;
}
}

- 8,242
- 3
- 31
- 55
-
6An additional reason for using an if instead of `?:` is that you can put breakpoints inside the if blocks. – Thorbjørn Ravn Andersen Jul 03 '11 at 13:03
If true -> 1
and false -> 0
mapping is what you want, you can do:
boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.

- 445,704
- 82
- 492
- 529
If you want to obfuscate, use this:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0

- 1,388
- 3
- 24
- 20
Lets play trick with Boolean.compare(boolean, boolean)
. Default behavior of function: if both values are equal than it returns 0
otherwise -1
.
public int valueOf(Boolean flag) {
return Boolean.compare(flag, Boolean.TRUE) + 1;
}
Explanation: As we know default return of Boolean.compare is -1 in case of mis-match so +1 make return value to 0 for False
and 1 for True

- 2,768
- 30
- 39
-
5`Boolean.compare(myBoolean, false)` would fit better accorning to the quoted description – Vadzim Sep 05 '16 at 20:03
-
@Vadzim Yes indeed will generate 1 and 0 by comparing with false and in current scenario it will generate 0 and -1. Both solutions are fine and +1 for your comment :-) – mumair Sep 06 '16 at 08:34
public static int convBool(boolean b)
{
int convBool = 0;
if(b) convBool = 1;
return convBool;
}
Then use :
convBool(aBool);

- 14,526
- 27
- 108
- 198