How is possible to apply toUpperCase() on an empty String in Java?

GniruT picture GniruT · Oct 10, 2015 · Viewed 8.1k times · Source

I've thought that if I run this

System.out.println("toUpperCase() on empty String:"+ "".toUpperCase());

and it returns an empty String. How is that possible? toUpperCase() should fail in this case isn't it? Thanks!

Answer

Eran picture Eran · Oct 10, 2015

Why should it fail? It converts any character of the input String to upper case. In your example, "any character" is equivalent to 0 characters.

The Javadoc doesn't say that it should fail for an empty String, which means it shouldn't fail :

Converts all of the characters in this String to upper case using the rules of the default locale. This method is equivalent to toUpperCase(Locale.getDefault()).

Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "title".toUpperCase() in a Turkish locale returns "T\u0130TLE", where '\u0130' is the LATIN CAPITAL LETTER I WITH DOT ABOVE character. To obtain correct results for locale insensitive strings, use toUpperCase(Locale.ENGLISH).

Returns: the String, converted to uppercase.