public class First
{
public static void main(String[] args)
{
String str1="Hello ",str2="World",str3="Hello World";
System.out.println(str3==("Hello "+"World")); //Prints true
System.out.println(str3==("Hello "+str2)); //Prints false
}
}
The reason of the above is given in JLS-
• Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
• Strings computed by concatenation at run time are newly created and therefore distinct.
What I wanted to ask is- Why the strings which are computed at run time differ from those which are computed at compile time? Is it because of the memory allocation,one is allocated memory in heap and one in String pool or there is some other reason?Please clarify.