+ 2

Why the ans is "false"?

According to me the answer should be true as s1 and s2 are same. https://code.sololearn.com/cc44B6WdqPIk/?ref=app

14th Oct 2023, 4:13 AM
Ayush Singh
Ayush Singh - avatar
4 odpowiedzi
+ 7
Hello, in java it checks to see if you are pointing to the same object. For example, you can say that person A is a substitute. And person B is a substitute. You would be correct that they are both substitutes, but not the same person. In java it checks to see if they are the same person. When you did new string it created a new object. You named it exactly the same thing but they are different. If you want to display true I think you use s1.equals(s2) which should check the characters of the strings
14th Oct 2023, 4:50 AM
Juan
Juan - avatar
+ 5
String variables are not simple variables, but reference variables, whose new value is created in the pool, and "new String()" always creates a new object with its own value store. So if they have the same values, then different storages cannot be equal in essence. That is, all these objects will be different: String s1 = "hello"; String s2 = new String(s1); String s3 = new String(s1); The second way to compare string values: String s1 = "hello"; String s2 = new String(s1); System.out. println(s1==s2.intern()); // true
14th Oct 2023, 7:15 AM
Solo
Solo - avatar
+ 4
String is an object and is stored on the heap. When you create a new object of the string class, Java creates a new variable with a different address in memory. By comparing s1 == s2 you compare two references, not the values stored there. Use equals s1.equals(s2)
14th Oct 2023, 7:36 AM
Николай
Николай - avatar