I am really confused with how string interning works in Java. When I write:
String a = "ABC";
String b = "ABC";
if (a==b)
System.out.println("Equal");
Does the compiler store the string literal "ABC" into the string constant pool at compile time?
That sounds illogical, because I thought the string constant pool was created by the JVM at runtime, and I don't see how that is possible if it is done at compile time since the Java compiler does not even invoke the JVM.
If it is not done at compile time and it is done at runtime then why does the following return false (taken from this answer)?
// But .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) // --> false
If it is done at runtime then why can't the JVM figure out that they are the same string?
I am really confused as to how string interning works in Java and where exactly the Java string pool is stored.