class Test {     public static void main() {         String s1 = null + null; //shows compile time error         String s1 = null;         String s2 = s1 + null;   //runs fine     } }   Can anybody please explain the reason for this behavior?
This code:
String s1 = null + null;   tries to perform addition operation on two null, which is not valid.
while here:
String s1 = null; String s2 = s1 + null;   You assigned null to s1. Then you perform concatenation of s1 and null. The type of s1 is String, so null in s1 + null will be converted to "null" string as per the String conversion rules, as in JLS §15.1.11 - String Conversion:
If the reference is null, it is converted to the string
"null"(four ASCII charactersn, u, l, l).Otherwise, the conversion is performed as if by an invocation of the
toStringmethod of the referenced object with no arguments; but if the result of invoking thetoStringmethod isnull, then the string"null"is used instead.
and concatenation will be done as - s1 + "null";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With