Question about String.toUpperCase behaviour

Florian Weimer fw at deneb.enyo.de
Mon Oct 28 20:34:58 UTC 2019


* Сергей Цыпанов:

> 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.


More information about the core-libs-dev mailing list