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
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
.
Probably something like this:
int i == 0 ? false : true;
or the other way round:
int i == 1 ? true : false
...
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.
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
.
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 )
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.