Home >Java >javaTutorial >Why Does `==` Comparison of Final Strings in Java Sometimes Return True and Sometimes False?

Why Does `==` Comparison of Final Strings in Java Sometimes Return True and Sometimes False?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 16:42:14250browse

Why Does `==` Comparison of Final Strings in Java Sometimes Return True and Sometimes False?

Comparing Final Strings with == in Java

Strings in Java, being immutable, behave uniquely when declared as final. Consider the following code:

String str1 = "str";
String str2 = "ing";
String concat = str1 + str2;

System.out.println(concat == "string"); // false

Here, the comparison returns false, as "==" compares object references. However, if we declare the strings final:

final String str1 = "str";
final String str2 = "ing";
String concat = str1 + str2;

System.out.println(concat == "string"); // true

Now, the comparison inexplicably returns true.

Reason

Final strings that are initialized with compile-time constant expressions, like the example above, become constant variables and acquire a unique property: they are interned. Interning means that unique instances of strings are shared.

In the second code snippet, the concatenation result "string" is interned at compile time. Thus, it shares the same reference as the string literal "string" passed to "==". This results in the true comparison.

Bytecode Analysis

The difference between the two versions can be seen in their bytecode:

  • Non-final version: Creates StringBuilder and concatenates strings at runtime, creating a new String object.
  • Final version: Inlines the concatenated string "string" at compile time, directly using referenced interned instances.

Conclusion

Final strings with compile-time constant expressions in Java are interned and share unique instances. This can lead to unexpected results when comparing them using "==" as it directly checks object references rather than their values.

The above is the detailed content of Why Does `==` Comparison of Final Strings in Java Sometimes Return True and Sometimes False?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn