`null` is treated as String?
For , s = s + "hai";
Internally, String.valueOf(null)
will be called. That method will convert null
to "null"
.
Byte code :
public static void main(java.lang.String[]) throws java.lang.Exception;
0: aconst_null
//some code
10: invokestatic #27; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;// check this line
// some other code
27: return
No it wont.Compiler replaces String concatenation with StringBuilder
operations which doesn't give null pointer exception.Compiler does all this backend and saves our time of writing boiler-plate code.Actually there is no such thing as String
concatenation as String is immutable
Decompiled code:-
String s = null;
s = (new StringBuilder(String.valueOf(s))).append("hai").toString();
System.out.println(s);
So,the answer to your question.
-
Compiler internally changes
+
concatenation operations usingStringBuilder
andString.valueOf
operations.So the compiler makes sure that null cases would be handled -
While using a
.
operator on aString
instance,you invoke methods defined in aString
instance such asString.concat(String str)
which will give a NullPointerException if yourString
instance is null