Java null String equals result

后端 未结 8 718
星月不相逢
星月不相逢 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:42

    That piece of code will throw a NullPointerException whenever string1 is null and you invoke equals on it, as is the case when a method is implicitly invoked on any null object.

    To check if a string is null, use == rather than equals.

    Although result1 and result3 will not be set due to NullPointerExceptions, result2 would be false (if you ran it outside the context of the other results).

提交回复
热议问题