String a="A";
String b="B";
final String c="C";
final String d="D";
String e=a+b;
String f=a+b;
System.out.println(e==f);//false
String g=c+d;
String h=c+d;
System.out.println(g==h);//true
Why it is so? String objects are created in a special memory are called string constant pool. But here what is the significance of final variable.
The compiler sees that c and d are final. This means that the compiler knows that c and d will never change. It thus compiles the code to
g and h are thus two references to the same STring literal, which is interned.
He can’t optimize e and f the same way, because a and b are not final and can thus change.