Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings in Java : equals vs == [duplicate]

Possible Duplicate:
How do I compare strings in Java?

  String s1 = "andrei";
  String s2 = "andrei";

  String s3 = s2.toString();

  System.out.println((s1==s2) + " " + (s2==s3));

Giving the following code why is the second comparison s2 == s3 true ? What is actually s2.toString() returning ? Where is actually located (s2.toString()) ?

like image 572
Andrei Ciobanu Avatar asked Jul 19 '10 13:07

Andrei Ciobanu


2 Answers

First of all String.toString is a no-op:

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

Second of all, String constants are interned so s1 and s2 are behind the scenes changed to be the same String instance.

like image 77
Robert Munteanu Avatar answered Oct 19 '22 05:10

Robert Munteanu


The method String.intern() can be used to ensure that equal strings have equal references. String constants are interned, so s1 and s2 will reference the same string. String.toString() simply returns itself, that is, a.toString() returns a, when a is a String. So, s2 also == s3.

In general, strings should not be compared by reference equality, but by value equality, using equals(). The reason is that it's easy to get two strings that are equivalent but different references. For example, when creating substrings. An exception to this rule is that if you know both strings have been interned beforehand (or you intern them as part of the comparison.)

To answer your implied question about heap or stack, Strings are allocated on the heap. Even if they were allocated on the stack, such as with the upcoming escape analysis and stack allocation, the semantics of the program will not change, and you will get the same result for both heap and stack allocation.

like image 31
mdma Avatar answered Oct 19 '22 06:10

mdma