What use does the == operator have for String?
java, string
Solution
Imagine a thread-safe `Queue<String>` acting as a communication channel between a producer thread and a consumer thread. It seems perfectly reasonable to use a special `String` to indicate termination.
// Deliberate use of `new` to make sure JVM does not re-use a cached "EOT".
private static final String EOT = new String("EOT");
...
// Signal we're done.
queue.put(EOT);
// Meanwhile at the consumer end of the queue.
String got = queue.get();
if ( got == EOT ) {
// Tidy shutdown
}
note that this would be resilient to:
queue.put("EOT");
because `"EOT" != EOT` even though `"EOT".equals(EOT)` would be `true`.
Problem
In Java, if one is to check if two Strings are equal, in the sense that their values are the same, he/she needs to use the `equals` method. E.g. : ``` String foo = "foo"; String bar = "bar"; if(foo.equals(bar)) { /* do stuff */ } ``` And if one wants to check for reference equality he needs to use the == operator on the two strings. ``` if( foo == bar ) { /* do stuff */ } ``` So my question is does the == operator have it's use for the String class ? Why would one want to compare String references ? Edit: What I am not asking : How to compare strings ? How does the == work ? How does the `equals` method work? What I am asking is what uses does the == operator have for String class in Java ? What is the justification of not overloading it, so that it does a deep comparison ?