0

[Java] Why do these strings return false?

I have this code in Java. The first comparison returns false (both are strings), the returns true (again, both strings). Why? public class Main { public static void main(String[] args) throws Exception { String s1 = new String("wow"); String s2 = "wow"; System.out.println(s1.getClass().getSimpleName()); //returns "String" System.out.println(s2.getClass().getSimpleName()); //returns "String" System.out.println(s1 == s2); //returns "false" String s3 = "wow"; String s4 = "wow"; System.out.println(s1.getClass().getSimpleName()); //returns "String" System.out.println(s2.getClass().getSimpleName()); //returns "String" System.out.println(s3 == s4); //returns "true" } } https://code.sololearn.com/ciypzm8n8bI2/?ref=app

8th Nov 2019, 7:53 AM
Fernando Pozzetti
Fernando Pozzetti - avatar
5 ответов
+ 3
Because, '==' is checks references, not the content comparison. And strings are immutable. In first case s1 contains reference to "wow" string of string pool. Where s1 directly points to "wow" string. In second case, s3,s4 are points to same location of string pool. Because of string immutability, strings not modifiable... Continued.
8th Nov 2019, 8:18 AM
Jayakrishna 🇮🇳
+ 4
When you create a string object using the string literal then JVM first checks whether the content matches with any content in the pool or not. If the content does not match then a new object is created but if the content matches then it will return the reference of that. So both string objects point to the same content. But, when you create string objects using new keyword, a new object is created whether the content is same or not.
8th Nov 2019, 8:34 AM
Avinesh
Avinesh - avatar
+ 3
Avinesh explained exact terms. s1 contains object reference, s2 contains string reference directly. Simply, when it involving references, you cannot have same references points to two different variable, unless until if you do like s2=s1; Using equals method s1.equals(s2); return true. Should be used for string equalence. read strings immutability for more info.
8th Nov 2019, 8:37 AM
Jayakrishna 🇮🇳
0
Thank you! So "new String" points to "wow" while s2 contains "wow"?
8th Nov 2019, 8:28 AM
Fernando Pozzetti
Fernando Pozzetti - avatar
0
Thanks to both of you! I was aware of string immutability, but I didnt know the rest!
8th Nov 2019, 9:00 AM
Fernando Pozzetti
Fernando Pozzetti - avatar