问题描述
请帮我看看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:
推荐答案
你不能使用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等于结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!