Comparing strings with == which are declared final in Java

I have a simple question about strings in Java. The following segment of simple code just concatenates two strings and then compares them with ==.

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

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

The comparison expression concat=="string" returns false as obvious (I understand the difference between equals() and ==).


When these two strings are declared final like so,

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

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

The comparison expression concat=="string", in this case returns true. Why does final make a difference? Does it have to do something with the intern pool or I’m just being misled?

6 Answers
6

Leave a Comment