0

Why does this return true? This seems a little odd since I have two Strings which are separate objects but are said to be aliases of each other.

public boolean stringEquals() {
  String tmp1 = "hello";
  String tmp2 = "hello";
  return tmp1==tmp2;

}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Amit
  • 157
  • 8
  • String interning - see [here](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839) – Avi Dec 04 '19 at 19:05
  • Because of JVM optimizations. You should always use `equals`. – Michael Dec 04 '19 at 19:05

2 Answers2

2

String literals are interned by the JVM, so their reference will be the same.

In other words, each String literal used will be stored exactly once, hence their object will be similar. See

enter image description here

Taken from here: https://www.geeksforgeeks.org/interning-of-string/

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
1

The == operator compares the reference of the 2 objects and not their values. So unless we use .equals() we must expect to see false as these are 2 separate objects.

But this special case happens with strings. In Java Strings are immutable. Meaning their value cannot change. JVM uses this property to optimize memory. The strings in Java are stored in a separate space in memory called String Pool. Since these 2 strings are the same and that they are immutable, JVM stores "hello" in the pool and reuses the same reference for both objects. This is safe as strings are immutable. ( If you assign it something else later in code, it would create a new value elsewhere in pool and reference to it).

At the same time it is interesting to note that this isn't the case when using constructor. If we use the constructor to construct a new string, it always creates a separate object with unique reference regardless of whether the value is same or not.

String a = new String("Hello");
String b = new String("Hello");
return a==b;

Would return false. The string pool concept applies only when using string literals without the constructor.

  • The = operator is an assignment, it doesn't compare anything. --- *"The strings in Java are stored in a separate space in memory called String Pool"* Incorrect. String *literals* are stored in the string pool. Strings in general are not. --- *"it would create a new value elsewhere in pool"* Nope, it would be elsewhere in *memory*. – Andreas Dec 04 '19 at 20:06