Assume two Java String objects:
String str = "<my string>";
String strLower = str.toLowerCase();
Is it then true that for every value of <my string>
the expression
str.length() == strLower.length()
evaluates to true
?
So, does String.toLowerCase()
preserve original string length for any value of String?
Also remember that toUpperCase() does not preserve the length either. Example: “straße” becomes “STRASSE” for the German locale. So you're more or less screwed if you're working with case sensitive strings and you need to store the index for something.
Surprisingly it does not!!
From Java docs of toLowerCase
Example:
First of all, I'd like to point out that I absolutely agree with the (currently highest-rated) answer of @codaddict.
But I wanted to do an experiment, so here it is:
It's not a formal proof, but this code ran for me without ever reaching the inside of theif
(using JDK 1.6.0 Update 16 on Ubuntu):Edit: Here's some updated code that handles Locales as well:
Running that code with the locale names mentioned in the accepted answer will print some examples. Running it without an argument will try all available locales (and take quite a while!).
It's not extensive, because theoretically there could be multi-character Strings that behave differently, but it's a good first approximation.Also note that many of the two-character combinations produced this way are probably invalid UTF-16, so the fact that nothing explodes in this code can only be blamed on a very robust String API in Java.
And last but not least: even if the assumption is true for the current implementation of Java, that can easily change once future versions of Java implement future versions of the Unicode standard, in which the rules for new characters may introduce situations where this no longer holds true.
So depending on this is still a pretty bad idea.