34

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.

condorcraft110 II
  • 261
  • 1
  • 2
  • 15
Mike
  • 47,263
  • 29
  • 113
  • 177

9 Answers9

51

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.

Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
NPE
  • 486,780
  • 108
  • 951
  • 1,012
6

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • I can in this simple example. In more complex code I *know* I'm going to instinctually want to use int as boolean because I have for so many years... Just wondering if there was anything syntactically I could do in Java to allow it or if I would just have to get used to this. – Mike Dec 10 '12 at 17:36
  • 8
    I would try to address your instinctive urge! An integer is distinct from a boolean, and if you use an integer, one day you're going to put an unexpected value into it. – Brian Agnew Dec 10 '12 at 17:39
  • `if you use an integer, one day you're going to put an unexpected value into it` totally correct. and +1 just for this. However what I was thinking about was more the return from function calls. I don't have a good "java" example at the moment, but I was thinking about the Linux `fork()`, if I don't care about the value of the result I can say `if(fork())` to cover both the case of a failed fork and the parent and the code internal to the conditional is just the child's. I like being able to do that, even if it is a little less readable. – Mike Dec 10 '12 at 17:48
  • 7
    @Mike: Java is NOT C. Methods should return a value on success and *throw an exception* on failure. *Please* do not use `int` as a return type, unless you are planning to return an actual number... – thkala Dec 10 '12 at 18:36
  • 2
    @thkala is correct, in a Java environment other developers will expect an exception in case of a failure, not a "magic number" return value; up the call stack the exception can be caught, instead of checking for the specific magic number. Some conventions just don't transfer between languages, due to the spec of the language (integer having no implicit boolean representation) or additional features in the language (checked exceptions). – Matt Dec 10 '12 at 18:53
6

Try BooleanUtils from Apache common-lang.

  BooleanUtils.toBoolean(0) = Boolean.FALSE
  BooleanUtils.toBoolean(1) = Boolean.TRUE
  BooleanUtils.toBoolean(2) = Boolean.TRUE
Tioma
  • 2,120
  • 9
  • 35
  • 52
3

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 )
Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
PermGenError
  • 45,977
  • 8
  • 87
  • 106
2

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.

Shubham Avasthi
  • 192
  • 4
  • 16
Fyre
  • 1,180
  • 8
  • 12
0

You could try something like that. Boolean i = true; if (i) System.out.println("i is true");

Just initialize it as a boolean value rather than an integer.

Butter Beer
  • 1,100
  • 3
  • 16
  • 32
0

If you insist to use int instead of boolean, just use a method to convert

class BooleanHelper
{
   public static boolean toBoolean (int pVal) {
      return pVal != 0;
   }
 ...
}

// apply

if (BooleanHelper.toBoolean(i)) { // BooleanHelper could be avoided using static imports...

However, just use

if (i != 0) {

is still shorter and clearer.

stefan bachert
  • 9,413
  • 4
  • 33
  • 40
  • `is still shorter and clearer.` true, but I do like the concept of the "helper" function, +1 for it. Thanks. – Mike Dec 10 '12 at 17:57
  • 4
    Oh dear god do NOT go down this route! [Madness awaits!](http://us.thedailywtf.com/Articles/Comparejava.aspx) – Izkata Dec 10 '12 at 19:22
0

You could create your own enum if you would like to preserve semantics. Actually, you only need a single value enum, then you can directly compare its ordinal position.

enum bool{FALSE};

if(i != bool.FALSE.ordinal()){
   //true case logic
   }
else{ //false case logic
   }
douglas
  • 116
  • 3
-1

Probably something like this:

int i == 0 ? false : true;

or the other way round:

int i == 1 ? true : false

...

Wingie
  • 111
  • 1
  • 2
  • 10