Java null String equals result

2020-02-10 04:14发布

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;

    //1st case
    String string1 = null;
    String string2 = null;
    result = string1.equals(string2);
    //2nd case
    String string1 = "something";
    String string2 = null;
    result2 = string1.equals(string2);
    //3rd case 
    String string1 = null;
    String string2 = "something";
    result3 = string1.equals(string2);

What the values of results are? I expect this values:

result1 is true;
result2 is false;
result3 is false;

7条回答
家丑人穷心不美
2楼-- · 2020-02-10 04:46

To prevent NPE while comparing Strings if at least one of them can be null, use StringUtils.equals method which is null-safe.

查看更多
登录 后发表回答