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:
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!