Alex Rivera | Logout

Does Java's toLowerCase() preserve original string length?

Asked 2010-03-01T16:32:44.053
30

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?

Edit
Report

1 Answer

4

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 the if (using JDK 1.6.0 Update 16 on Ubuntu):

Edit: Here's some updated code that handles Locales as well:

import java.util.Locale;

public class ToLowerTester {
    public final Locale locale;

    public ToLowerTester(final Locale locale) {
        this.locale = locale;
    }

    public String findFirstStrangeTwoLetterCombination() {
        char[] b = new char[2];
        for (char c1 = 0; c1 < Character.MAX_VALUE; c1++) {
            b[0] = c1;
            for (char c2 = 0; c2 < Character.MAX_VALUE; c2++) {
                b[1] = c2;
                final String string = new String(b);
                String lower = string.toLowerCase(locale);
                if (string.length() != lower.length()) {
                    return string;
                }
            }
        }
        return null;
    }
    public static void main(final String[] args) {
        Locale[] locales;
        if (args.length != 0) {
            locales = new Locale[args.length];
            for (int i=0; i<args.length; i++) {
                locales[i] = new Locale(args[i]);
            }
        } else {
            locales = Locale.getAvailableLocales();
        }
        for (Locale locale : locales) {
            System.out.println("Testing " + locale + "...");
            String result = new ToLowerTester(locale).findFirstStrangeTwoLetterCombination();
            if (result != null) {
                String lower = result.toLowerCase(locale);
                System.out.println("Found strange two letter combination for locale "
                    + locale + ": <" + result + "> (" + result.length() + ") -> <"
               
answered 2010-03-01T17:05:36.190

Your Answer