Convert boolean to int in Java
Solution 1
int myInt = myBoolean ? 1 : 0;
^^
PS : true = 1 and false = 0
Solution 2
int val = b? 1 : 0;
Solution 3
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);
}
Solution 4
boolean b = ....;
int i = -("false".indexOf("" + b));
Solution 5
import org.apache.commons.lang3.BooleanUtils;
boolean x = true;
int y= BooleanUtils.toInteger(x);
hpique
iOS, Android & Mac developer. Founder of Robot Media. @hpique
Updated on July 08, 2022Comments
-
hpique almost 2 years
What is the most accepted way to convert a
boolean
to anint
in Java? -
rsp over 13 yearsIn the case where myBoolean stands for a boolean expression, using parenthesis is more readable.
-
Andrew Simpson over 13 yearsYes, as in
(foo && (!bar || baz)) ? 1 : 0
. Obviously, if it's just an identifier, the parens aren't necessary or desirable. -
matbrgz almost 13 yearsWill be inlined by modern JIT's, so not necessarily inefficient. Also it documents why the b.compareTo is being used so it is readable.
-
matbrgz almost 13 yearsAn additional reason for using an if instead of
?:
is that you can put breakpoints inside the if blocks. -
barjak almost 13 yearsIt 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.
-
arkon almost 11 years@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.
-
matbrgz almost 11 years@b1naryatr0phy you are micro-optimizing prematurely.
-
arkon almost 11 years@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.
-
matbrgz almost 11 years@b1naryatr0phy if you call a slow method a gazillion times your boss should lecture you on memoization instead.
-
arkon almost 11 years@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.
-
matbrgz almost 11 years@b1naryatr0phy So if I used
Boolean.toString(b)
instead of"" + b
in order to avoid the string concatenation that would be ok with you? -
Mike Baxter almost 11 yearsIts 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.
-
shmosel over 9 years1. You can use
Boolean.compare()
and avoid the autoboxing. 2. The documentation forBoolean.compareTo()
does not say it will return 1, only "a positive value if this object represents true and the argument represents false". -
Mapsy over 9 yearsI 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.
-
matbrgz over 9 years@AlexT. if you do microbenchmarks you should use a framework to ensure that you measure correctly. See openjdk.java.net/projects/code-tools/jmh.
-
Mapsy over 9 years@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.
-
mumair over 8 yearsnice trick with boolean! I was looking might some casting exist like (int) true = 1, but noting exist like this :P
-
Montaro over 8 yearsI really needed
Boolean#compare
;) -
kevinarpe over 8 years@kennytm: Brilliant hack... but tiny nit pick: If
b
is primitiveboolean
, I think you need to use:5 - Boolean.toString(b).length
-
dixhom about 8 yearsfor beginners like me,
(boolean expression) ? 1 : 0;
would be more understandable. I thinkmy
prefix made it look like a variable. -
Andrew Tobilko about 8 years@kevinarpe, then
5 - Boolean.toString(b).length()
-
Konrad Morawski about 8 years@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) -
Vadzim over 7 years
Boolean.compare(myBoolean, false)
would fit better accorning to the quoted description -
mumair over 7 years@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 :-)
-
matbrgz almost 7 years@AlexT. I did not conclude anything. Perhaps you could make your test available so we can reproduce it?
-
royhowie over 4 years@KonradMorawski in what way does
foo && (!bar || baz) ? 1 : 0
cause a syntax error??:
has lower precedence than both&&
and||
. -
Solomon Ucko about 4 yearsFWIW,
BooleanUtils.toInteger
is implemented as justreturn bool ? 1 : 0;
. -
Solomon Ucko about 4 yearsFWIW,
BooleanUtils.toInteger
is implemented as justreturn bool ? 1 : 0;
. -
MuhsinFatih almost 4 yearsI'm going to upvote if this is sarcasm, in which case it's hilarious. I just can't figure if it is
-
Gaurav almost 4 yearsperfect answer!
-
Eric Duminil almost 4 yearsApache Commons can be useful, but this is just ridiculous.
-
ardnew almost 4 yearsnow with even more truth
int myInt = myBoolean ? ~0 : 0
-
Ankit almost 4 yearsI put an edit that added examples of how to use it in the middle of a numerical expression.
-
Michał Mirowski over 3 yearsBeautifully elegant :)
-
Pat Lee almost 3 years@EricDuminil This can slightly increase readability in case of nested ( ? : ) or long one-liners.
-
user1438038 almost 3 yearsEven 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.
-
bb1950328 over 2 years@EricDuminil IMO
xyz.stream().map(BooleanUtils::toInteger)
is much more readable thanxyz.stream().map(x -> x ? 1 : 0)
-
Eric Duminil over 2 years@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 stackoverflow.com/a/3794521/6419007 instead.