Checking the "boolean" result of an "int" type

95,566

Solution 1

In Java,

if ( i != 0 )

is the idiomatic way to check whether the integer i differs from zero.

If i is used as a flag, it should be of type boolean and not of type int.

Solution 2

Why not use the boolean type ? That will work as you expect without the potentially problematic integer/boolean conflation.

private boolean isValid;
...
if (!isValid) {
   ...
}

Note that this is the idiomatic Java approach. 3rd party libs use this, and consumers of your API will use and expect it too. I would expect libs that you use to give you booleans, and as such it's just you treating ints as booleans.

Solution 3

Try BooleanUtils from Apache common-lang.

  BooleanUtils.toBoolean(0) = Boolean.FALSE
  BooleanUtils.toBoolean(1) = Boolean.TRUE
  BooleanUtils.toBoolean(2) = Boolean.TRUE

Solution 4

FROM JLS:

The boolean type has two values, represented by the boolean literals true and false, formed from ASCII letters.

Thus no is the answer. the only was is

if ( i != 0 )

Solution 5

In java the condition has to be of type boolean else it can't be an expression, that is why

if( i ) 

is not allowed.

It has to be either true or false.

Share:
95,566
Mike
Author by

Mike

Have a BS in computer science from SIUE Worked @ Motorola for 6 years as an embedded systems software engineer Currently reside in OH working for Emerson as a software engineer

Updated on June 17, 2020

Comments

  • Mike
    Mike almost 4 years

    I'm learning Java, coming from C and I found an interesting difference between languages with the boolean type. In C there is no bool/ean so we need to use numeric types to represent boolean logic (0 == false).

    I guess in Java that doesn't work:

    int i = 1;
    if (i)
        System.out.println("i is true");
    

    Nor does changing the conditional via a typecast:

    if ((boolean)i)
    

    So besides doing something like:

    if ( i != 0 )
    

    Is there any other way to do a C-ish logic check on an int type? Just wondering if there were any Java tricks that allow boolean logic on non-boolean types like this.


    EDIT:
    The example above was very simplistic and yields itself to a narrow scope of thinking. When I asked the question originally I was thinking about non-boolean returns from function calls as well. For example the Linux fork() call. It doesn't return an int per se, but I could use the numeric return value for a conditional nicely as in:

    if( fork() ) {
        // do child code
    

    This allows me to process the code in the conditional for the child, while not doing so for the parent (or in case of negative return result for an error).

    So I don't know enough Java to give a good "Java" example at the moment, but that was my original intent.