java 为什么 String 用 + 运算符连接 null 并用 concate() 方法抛出 NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30003211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why String concatenate null with + operator and throws NullPointerException with concate() method
提问by kavi temre
Here is my class, where i am concatenating two string.
String concatenate with null
using + operator execute smoothly but throws NullPointerException
with concate()
method.
这是我的班级,我在那里连接两个字符串。字符串连接null
使用 + 运算符执行顺利但NullPointerException
使用concate()
方法抛出。
public class Test {
public static void main(String[] args) {
String str="abc";
String strNull=null;
System.out.println(strNull+str);
str.concat(strNull);
}
}
can anybody tell me the reason behind it ??
有人能告诉我背后的原因吗??
回答by silentprogrammer
Case 1:
情况1:
System.out.println(strNull+str); // will not give you exception
From the docs(String conversion)
从文档(字符串转换)
If the reference is null, it is converted to the string "null"(four ASCII characters n, u, l, l).
Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
如果引用为空,则将其转换为字符串“空”(四个 ASCII 字符 n、u、l、l)。
否则,转换就像通过调用不带参数的引用对象的 toString 方法来执行一样;但如果调用 toString 方法的结果为 null,则使用字符串“null”代替。
Case 2:
案例2:
str.concat(strNull); //NullPointer exception
If you see the sourceof concat(String str)
it uses str.length();
so it would be like null.length()
giving you a NullPointerException
.
如果您看到它使用的来源,concat(String str)
那么str.length();
就像null.length()
给您一个NullPointerException
.
回答by Zigac
If you see in java.lang.String source, and use null as parameter. NPE is thrown in first line in length() method.
如果在 java.lang.String 源码中看到,并使用 null 作为参数。NPE 被抛出到 length() 方法的第一行。
public String concat(String str) {
int otherLen = str.length();//This is where NullPointerException is thrown
if (otherLen == 0) {
return this;
}
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
回答by Hyman
@Blip : 1) null + "ABC"
@Blip: 1)空+“ABC”
Straight forward answer to your question is + operator in java uses StringBuilder.append method to concat the strings.
您的问题的直接答案是 + 运算符在 java 中使用 StringBuilder.append 方法来连接字符串。
And StringBuilder.append() method treats null object as "null" String. Hence null + "ABC" won't give Null Pointer exception but rather prints nullABC.
而 StringBuilder.append() 方法将空对象视为“空”字符串。因此 null + "ABC" 不会给出空指针异常,而是打印 nullABC。
2) String.concat()
2) String.concat()
And yes, there is no null check before string.length() method in concat() function of String class. Hence it is throwing null pointer exception.
是的,在 String 类的 concat() 函数中的 string.length() 方法之前没有空检查。因此它抛出空指针异常。
Hope this answers your question.
希望这能回答你的问题。
回答by sol4me
Because inside concat
method in String class, length
method is getting invoked on passed parameter , due to which NPE is thrown.
因为concat
String 类中的内部方法,length
在传递的参数上调用方法,因此抛出 NPE。
public String concat(String str) {
int otherLen = str.length();<------
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
回答by Muneeb Nasir
concate()
method creates new String()
object under the hood.
concate()
方法new String()
在引擎盖下创建对象。
where as +
combines\ concatenates values by using toString()
method. That's why when we use +
it continents "somevalue".append(null).toString()
.
其中 as +
combine\ 使用toString()
方法连接值。这就是为什么当我们使用+
它时 continents "somevalue".append(null).toString()
。
for referencesee this question.
供参考,请参阅此问题。
回答by kaykay
String.concat()
need an object of type String
as a parameter.
String.concat()
需要一个类型的对象String
作为参数。
There is no type which null
is an instanceof
. Refer JLS:
没有类型null
是instanceof
. 参考 JLS:
15.20.2 Type Comparison Operator instanceof
RelationalExpression: RelationalExpression instanceof ReferenceType At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
15.20.2 类型比较运算符 instanceof
RelationalExpression:RelationalExpression instanceof ReferenceType 在运行时,如果 RelationalExpression 的值不为空,并且可以将引用转换为 ReferenceType 而不会引发 ClassCastException,则 instanceof 运算符的结果为真。否则结果为假。
回答by java guy
Actual implementation of concate method is like this . this method need an object of type String as a parameter and if argument is null then it throws Null Pointer Exp.
concate 方法的实际实现是这样的。此方法需要一个 String 类型的对象作为参数,如果参数为 null,则抛出 Null Pointer Exp。
public String concat(String paramString)
{
int i = paramString.length();
if (i == 0) {
return this;
}
int j = this.value.length;
char[] arrayOfChar = Arrays.copyOf(this.value, j + i);
paramString.getChars(arrayOfChar, j);
return new String(arrayOfChar, true);
}
回答by MLavrentyev
The String
class holds an array (probably an ArrayList
) of characters. When you call .concat()
it goes through and adds every character from the second string to the first.
的String
类包含的阵列(可能是一个ArrayList
字符)。当您调用.concat()
它时,它会通过并将第二个字符串中的每个字符添加到第一个字符串中。
If the first String is null
, there is nothing to add to, causing a NullPointer Exception
. Try initializing String
s with ""
.
如果第一个 String 是null
,则无需添加任何内容,从而导致NullPointer Exception
. 尝试用 初始化String
s ""
。
回答by Jacare
Initializing a null String with ""
should work.
初始化一个空字符串""
应该可以工作。