Does java optimize operations with string literals? For example, does
\"literal\".toLowerCase()
always create a new string instance?
First of, I think that is unspecified, so the behavior might differ between JDKs.
However, in my Oracle JDK 1.8.0_131, when I look at the source code of String.toLowerCase(Locale), I see that there is a check that returns the string itself, if no characters need to be changed.
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstUpper = 0 ; firstUpper < len; ) {
// Basically
if(characterNeedsToBeChanged) {
break scan;
}
}
return this;
}
...
// Create a new string
....