Here is my class, where i am concatenating two string.
String concatenate with null
using + operator execute smoothly but throws NullPointerException
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.
If the first String is null
, there is nothing to add to, causing a NullPointer Exception
. Try initializing String
s with ""
.
String.concat()
need an object of type String
as a parameter.
There is no type which null
is an instanceof
. Refer 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.
Case 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.
Case 2:
str.concat(strNull); //NullPointer exception
If you see the source of concat(String str)
it uses str.length();
so it would be like null.length()
giving you a NullPointerException
.