Mike Mike - 16 days ago 4x
Java Question

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

I'm learning Java, coming from C and I found an interesting difference between languages with the

type. In C there is no
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
type? Just wondering if there were any Java tricks that allow boolean logic on non-boolean types like this.


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
call. It doesn't return an
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.


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.