Java null String等于结果 [英] Java null String equals result

查看:198
本文介绍了Java null String等于结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我看看java中的string.equals如何使用null值?异常有问题吗?
三种情况:

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为true;

result2为false;

result3是假的;

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


推荐答案

你不能使用dereference(dot,'。')运算符来如果该实例是 null ,则访问实例上的实例变量或调用方法。这样做会产生 NullPointerException

You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.

通常的做法是使用你知道的非null值字符串比较。例如,something.equals(stringThatMayBeNull)

It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).

这篇关于Java null String等于结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆