Checking the “boolean” result of an “int” type

旧街凉风 提交于 2019-12-01 14:55:53
NPE

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.

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.

PermGenError

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 )

Try BooleanUtils from Apache common-lang.

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

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.

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.

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.

Probably something like this:

int i == 0 ? false : true;

or the other way round:

int i == 1 ? true : false

...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!