Convert boolean to int in Java

505,506

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);
Share:
505,506
hpique
Author by

hpique

iOS, Android & Mac developer. Founder of Robot Media. @hpique

Updated on July 08, 2022

Comments

  • hpique
    hpique almost 2 years

    What is the most accepted way to convert a boolean to an int in Java?

  • rsp
    rsp over 13 years
    In the case where myBoolean stands for a boolean expression, using parenthesis is more readable.
  • Andrew Simpson
    Andrew Simpson over 13 years
    Yes, as in (foo && (!bar || baz)) ? 1 : 0. Obviously, if it's just an identifier, the parens aren't necessary or desirable.
  • matbrgz
    matbrgz almost 13 years
    Will 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
    matbrgz almost 13 years
    An additional reason for using an if instead of ?: is that you can put breakpoints inside the if blocks.
  • barjak
    barjak almost 13 years
    It 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
    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
    matbrgz almost 11 years
    @b1naryatr0phy you are micro-optimizing prematurely.
  • arkon
    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
    matbrgz almost 11 years
    @b1naryatr0phy if you call a slow method a gazillion times your boss should lecture you on memoization instead.
  • arkon
    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
    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
    Mike Baxter almost 11 years
    Its 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
    shmosel over 9 years
    1. 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".
  • Mapsy
    Mapsy over 9 years
    I 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
    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
    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
    mumair over 8 years
    nice trick with boolean! I was looking might some casting exist like (int) true = 1, but noting exist like this :P
  • Montaro
    Montaro over 8 years
    I really needed Boolean#compare ;)
  • kevinarpe
    kevinarpe over 8 years
    @kennytm: Brilliant hack... but tiny nit pick: If b is primitive boolean, I think you need to use: 5 - Boolean.toString(b).length
  • dixhom
    dixhom about 8 years
    for beginners like me, (boolean expression) ? 1 : 0; would be more understandable. I think my prefix made it look like a variable.
  • Andrew Tobilko
    Andrew Tobilko about 8 years
    @kevinarpe, then 5 - Boolean.toString(b).length()
  • Konrad Morawski
    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
    Vadzim over 7 years
    Boolean.compare(myBoolean, false) would fit better accorning to the quoted description
  • mumair
    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
    matbrgz almost 7 years
    @AlexT. I did not conclude anything. Perhaps you could make your test available so we can reproduce it?
  • royhowie
    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
    Solomon Ucko about 4 years
    FWIW, BooleanUtils.toInteger is implemented as just return bool ? 1 : 0;.
  • Solomon Ucko
    Solomon Ucko about 4 years
    FWIW, BooleanUtils.toInteger is implemented as just return bool ? 1 : 0;.
  • MuhsinFatih
    MuhsinFatih almost 4 years
    I'm going to upvote if this is sarcasm, in which case it's hilarious. I just can't figure if it is
  • Gaurav
    Gaurav almost 4 years
    perfect answer!
  • Eric Duminil
    Eric Duminil almost 4 years
    Apache Commons can be useful, but this is just ridiculous.
  • ardnew
    ardnew almost 4 years
    now with even more truth int myInt = myBoolean ? ~0 : 0
  • Ankit
    Ankit almost 4 years
    I put an edit that added examples of how to use it in the middle of a numerical expression.
  • Michał Mirowski
    Michał Mirowski over 3 years
    Beautifully elegant :)
  • Pat Lee
    Pat Lee almost 3 years
    @EricDuminil This can slightly increase readability in case of nested ( ? : ) or long one-liners.
  • user1438038
    user1438038 almost 3 years
    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.
  • bb1950328
    bb1950328 over 2 years
    @EricDuminil IMO xyz.stream().map(BooleanUtils::toInteger) is much more readable than xyz.stream().map(x -> x ? 1 : 0)
  • Eric Duminil
    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.