-2
String s1 = "java";

String s2 = "java";

System.out.println(s1==s2);  //true
System.out.println(""+s1==s2); //false

why the output is so?

in the second case only added "" quotes.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Anis Mulla
  • 75
  • 7
  • 2
    you can't say "solved" when the question is "why the output". If you would've said: "How to prinln true regardless of adding `""+`" then yes, you solved the problem – Adelin Jan 17 '18 at 06:37
  • https://stackoverflow.com/questions/10578984/what-is-string-interning – Codebender Jan 17 '18 at 06:37
  • you are getting confused with references comparison and values comparisons and last but not least watch out to the `String pool` – Allan Jan 17 '18 at 06:41

1 Answers1

4
  • == compares references of two string objects which will be different for the two cases above.
  • .equals() compares the value of the 2 string objects
  • for String objects the String pool will save some memory by regrouping to the same place in memory different String objects with the same value.

Look at the following code to understand how it works:

String s1 = "java";//first string
String s2 = "java";//thanks to string pool the s2 is actually using the same memory location as s1 (saving space for same value string objects)

System.out.println(s1==s2);  //true ref comparison equals thanks to string pool intervention
System.out.println(""+s1==s2); //false (the resulting string of ""+s1 is stored in a different place in memory than s4
System.out.println(""+(s1==s2));//true due to string pool
System.out.println(s1.equals(s2));  //true -> value comparison
System.out.println(s2.equals(""+s1)); //true -> value comparison


String s3 = new String("java");//this construction does not let the string pool intervene
String s4 = new String("java");//2 different memory locations for those 2 objects

System.out.println(s3==s4);  //false no string pool intervention -> 2 different memory locations
System.out.println(""+s3==s4); //false false (the resulting string of ""+s3 is stored in a different place in memory than s4
System.out.println(""+(s3==s4));//false no string pool intervention -> 2 different memory locations
System.out.println(s3.equals(s4));  //true -> value comparison
System.out.println(s4.equals(""+s3)); //true -> value comparison
Allan
  • 12,117
  • 3
  • 27
  • 51
abhiroxx
  • 116
  • 6