why "abc" + null results abcnull
String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;
System.out.println(s3);
Result: abcnull
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because Java will create a StringBuilder to append
s1, or"abc",tos2, ornull.According to the spec for StringBuilder.append(String)–
So it turns into the same as
"abc" + "null"Let’s take your code example (I placed it inside a method):
If we take a gander at the bytecode (gotten by invoking javap -c):
Java creates a
StringBuilderand appends the values, asStrings, ofs1ands2.So you have to be careful then, if you were expecting a NullPointerException, because concatenation in Java will skirt the issue.
Side Note: As pointed out by Jon Skeet, this is ultimately just implementation details — it’s the Java spec that guarantees that null, when converted to a String, turns into “null”. However, this bytecode at least shows what is actually happening behind the scenes.