Question about String.toUpperCase behaviour
Rob Spoor
openjdk at icemanx.nl
Tue Oct 29 20:12:39 UTC 2019
On 28/10/2019 21:34, Florian Weimer wrote:
> * Сергей Цыпанов:
>
>> Hello,
>>
>> current implementation of e.g. String.toUpperCase() returns the object
>> it was called on in case all code points are in upper case.
>>
>> E.g. this test
>>
>> @Test
>> public void upperCase() {
>> String str = "AZ"; // English
>> assert str == str.toUpperCase();
>>
>> str = "АЯ"; // Russian
>> assert str == str.toUpperCase();
>> }
>>
>> passes for both Latin-1 and UTF-16. This assumption allows to simplify this:
>>
>> boolean isUpperCase = str.toUpperCase().equals(str);
>>
>> to
>>
>> boolean isUpperCase = str.toUpperCase() == str;
>>
>> Could this transformation be legal assuming that existing behaviour of
>> String.toUpperCase is not documented?
>
> Valid for whom? For the JDK itself, sure. But programmers really
> should not assume such undocumented behavior when writing Java
> programs, and neither shoud external tools targeting the JVM.
>
I agree. There is no reason to use == instead of equals. Not for
readability, because it will most likely confuse people who will come
asking why you're not using equals. Not for performance, because since
at least Java 7 String.equals starts with this:
if (this == anObject) {
return true;
}
So in other words: keep using equals, it's the cleaner option.
More information about the core-libs-dev
mailing list