0

Why is the result false?

String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = s1+s2;
System.out.println(s3==s4);

As I know, there's already one "helloworld" in the constant pool.

Thanks for answering, but what I want to ask is not the difference between "==" and "equals", I just want to make sure s1+s2; makes a new String, even though there's already one String Object with value "helloworld" in memory.

EvanSWFeng
  • 61
  • 3
  • Use .equals() i.e., s3.equals(s4) – Beshambher Chaukhwan Feb 25 '21 at 06:55
  • @BeshambherChaukhwan I think the point is that it isn't pointing to the same string instance. Not that the strings aren't equal in value. – Paul Rooney Feb 25 '21 at 06:57
  • 2
    s4 will create a new String and so == comparison fails. == only works for String literals and not for variables – Mohammad Feb 25 '21 at 06:57
  • Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – mehowthe Feb 25 '21 at 06:59
  • 1
    You probably expect that `String s4 = s1+s2;` gets optimized away at compile-time. But it doesn't, it will still be a statement at run-time. Therefore, you're creating a new `String` there. – akuzminykh Feb 25 '21 at 06:59
  • I had the same question earlier. Please check this https://stackoverflow.com/a/61588929?noredirect=1 – Mohammad Feb 25 '21 at 07:00

2 Answers2

0

You need to understand that they all are object instance of class String

String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";

This creates 3 objects with different values and different memory

String s4 = s1+s2;

Now you are again creating a new object with same value as s1 and s2 but since its a new object it has different memory.

 System.out.println(s3==s4);

Now with this line you are trying to compare the values for these 2 objects and in String class the correct way to do it is by using equals() method i.e.,

System.out.println(s3.equals(s4));

For detailed information please check this:
https://www.geeksforgeeks.org/difference-equals-method-java/

Beshambher Chaukhwan
  • 1,418
  • 2
  • 9
  • 13
0

(s3==s4) - means comparing references, not values. reference s3 is not the same as reference s4. s3 and s4 are two different instances of String. use equals for comparing values of objects. override equals for your own classes if it necessary.

Tobias
  • 2,547
  • 3
  • 14
  • 29