Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Strings subtle differences

Tags:

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?

like image 920
Aamir Avatar asked Apr 09 '14 17:04

Aamir


1 Answers

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 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.

and concatenation will be done as - s1 + "null";

like image 97
Rohit Jain Avatar answered Sep 18 '22 04:09

Rohit Jain