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

前端 未结 8 1518
死守一世寂寞
死守一世寂寞 2020-12-10 23:43

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

相关标签:
8条回答
  • 2020-12-11 00:11

    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.

    0 讨论(0)
  • 2020-12-11 00:11

    Probably something like this:

    int i == 0 ? false : true;

    or the other way round:

    int i == 1 ? true : false

    ...

    0 讨论(0)
  • 2020-12-11 00:12

    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.

    0 讨论(0)
  • 2020-12-11 00:13

    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.

    0 讨论(0)
  • 2020-12-11 00:13

    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 )
    
    0 讨论(0)
  • 2020-12-11 00:13

    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 讨论(0)
提交回复
热议问题