Java null String equals result

后端 未结 8 738
星月不相逢
星月不相逢 2020-12-16 15:11

Please help me how does the string.equals in java work with null value? Is there some problem with exceptions? Three cases:

boolean result1,result2, result3;         


        
8条回答
  •  盖世英雄少女心
    2020-12-16 15:40

    Our most common use-case of this type of thing is when we have a database field that contains "Y" or "N" to represent a Boolean (it's an old system, don't ask).

    Thus, we do this:

    if ("Y".equals(stringObjectThatMayBeNull) ? result : otherResult);

    Instead of this:

    if (stringObjectThatMayBeNull.equals("Y") ? result : otherResult);

    ... which avoids a NullPointerException when executing the .equals method.

提交回复
热议问题