0
public static void main(String[] args) {
String s="";
String s1=null;
String s2="null";
for(int i=0;i<2;i++) {
s+=i;
s1+=i;
s2+=i;
}
System.out.println(s);
System.out.println(s1);
System.out.println(s2);
}

I understand why an empty string will give 01 as a result. But I don't understand why s1 and s2 values will be the same. While s1 is null and s2 has null as a string value. Still, they give the same answer.

secretLion
  • 55
  • 5
  • 4
    The loop part is irrelevant. All this is about is how string concatenation behaves with `null`, and that refers to "String Conversion" in the JLS: https://docs.oracle.com/javase/specs/jls/se10/html/jls-5.html#jls-5.1.11 "If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l)." – Jon Skeet Jul 12 '20 at 16:01
  • @JonSkeet okay i understood. Thank you. I am new to java so i didn't knew this one. – secretLion Jul 12 '20 at 16:14

0 Answers0