Does java optimize operations with string literals? For example, does
"literal".toLowerCase()
always create a new string instance?
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.
toLowerCase()
callstoLowerCase(Locale.getDefault())
.Looking at the implementation you'll see that the original
String
is returned if no characters need to be changed: