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.

14
  • 11
    No. (comment is NOT too short)
    – tckmn
    Dec 10, 2012 at 17:31
  • 2
    @sampson-chen - that's boolean to an int, mine is int to a boolean... or are you considering that question the same?
    – Mike
    Dec 10, 2012 at 17:37
  • 1
    @Mike oops, apologies; that's my mistake there. Dec 10, 2012 at 17:46
  • 2
    In C there is no bool - Er, yes there is. Dec 10, 2012 at 20:44
  • 3
    @BlueRaja-DannyPflughoeft - "The standard types in C, that is without including <bool.h>, do not include a bool type." - Is that better?
    – Mike
    Dec 10, 2012 at 20:49

9 Answers 9

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.

4
  • 1
    Got it, I guess I'll have to get used to having to write all those extra (!=) characters... thanks!
    – Mike
    Dec 10, 2012 at 17:39
  • 9
    I think the real idiom is to use booleans. The above is a code smell, IMHO Dec 10, 2012 at 17:42
  • 7
    Use booleans when you're only doing logic; do != 0 when there's an actual meaningful number. Dec 10, 2012 at 17:50
  • How would one go about (n & 1) to check whether even or odd? stick a == or != 0 at the end?
    – AgentM
    Nov 9, 2020 at 20:16
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.

5
  • 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, 2012 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. Dec 10, 2012 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, 2012 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, 2012 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, 2012 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
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 )
2
  • Nice link... Oracle is the keeper of the "official" Java documentation?
    – Mike
    Dec 10, 2012 at 17:40
  • 1
    @Mike - yes. Sun was bought out by Oracle Dec 10, 2012 at 17:46
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.

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.

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.

2
  • is still shorter and clearer. true, but I do like the concept of the "helper" function, +1 for it. Thanks.
    – Mike
    Dec 10, 2012 at 17:57
  • 4
    Oh dear god do NOT go down this route! Madness awaits!
    – Izkata
    Dec 10, 2012 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
   }
-1

Probably something like this:

int i == 0 ? false : true;

or the other way round:

int i == 1 ? true : false

...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.