-3

I have been told in a Java course at my university that I should never compare Java strings with the == operator, because it checks if two strings are the same object instead of checking if they have the same characters.

However, on the day of the exam, I am presented with the following code:

if ("String".toString() == "String") 
  System.out.println("The same");
else
  System.out.println("Not the same");

I thought the result was going to be "Not the same", because "String".toString() and "String" are not the same object.

However, the console prints "The same"!. ¿How does string comparison with == actually work?

Arnold Gee
  • 856
  • 2
  • 8
  • 18
  • 1
    Did you read the [docs](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/String.html#toString())? `toString` returns the same object. – Sweeper May 09 '21 at 07:59
  • But I thought the "String" on the left and the "String" on the right were different objects anyways. – Arnold Gee May 09 '21 at 07:59
  • Because they *aren't* different objects, of course. – user207421 May 09 '21 at 08:05
  • Here is actual reason why two string objects have the same references [How and where does String literals in Java stored in the memory](https://www.tutorialspoint.com/how-and-where-does-string-literals-in-java-stored-in-the-memory) – Lukasz Blasiak May 09 '21 at 08:07

1 Answers1

3

If you look at String's toString() you'll see that it returns this (i.e. the same String instance on which it was executed):

/**
 * This object (which is already a string!) is itself returned.
 *
 * @return  the string itself.
 */
public String toString() {
    return this;
}

Therefore

"String".toString() == "String"

is equivalent to

"String" == "String"

which returns true, since both are String literals having the same value, so they are the same object.

A String literal is automatically added to the String pool, so all the places in the source code where you write the same String literal (such as "String") will return the same object from the String pool.

Eran
  • 387,369
  • 54
  • 702
  • 768