Here is my class, where i am concatenating two string.
String concatenate with null
using + operator execute smoothly but throws NullPointerException
Initializing a null String with ""
should work.
concate()
method creates new String()
object under the hood.
where as +
combines\ concatenates values by using toString()
method. That's why when we use +
it continents "somevalue".append(null).toString()
.
for reference see this question.
If you see in java.lang.String source, and use null as parameter. NPE is thrown in first line in length() method.
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);
}
Because inside concat
method in String class, length
method is getting invoked on passed parameter , due to which NPE is thrown.
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);
}
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.
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);
}
@Blip : 1) null + "ABC"
Straight forward answer to your question is + operator in java uses StringBuilder.append method to concat the strings.
And StringBuilder.append() method treats null object as "null" String. Hence null + "ABC" won't give Null Pointer exception but rather prints nullABC.
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.
Hope this answers your question.