Monday, February 4, 2013

Implicitly using the default locale is a common source of bugs

Locale represents a language/country/variant combination. Locales are used to alter the presentation of information such as numbers or dates to suit the conventions in the region they describe.

When you call toLowerCase(), internally toLowerCase(Locale.getDefault()) is getting called.

Calling str.toLowerCase() str.UpperCase without specifying explicit local is common sourse of bug. The reason is that those method uses the current locale of that device ex in Turkish uppercase replacement of "i" is not "I".

You can set locale by using:

Locale.setDefault(new Locale("US"));

You can get locale by using:

Locale loc = Locale.getDefault();

Now you can use custom/default locale:

String class toLowerCase(Locale locale) method example. This example shows you how to use toLowerCase(Locale locale)method.This method Converts all of the characters in this String to lower case using the rules of the given Locale. 

import java.util.Locale;

public class UpperLowerCase
{
    public static void main(String[] args)
    {
        String str = "String to Upper or lower Based on Locale";

        // Get user's default locale
        Locale loc = Locale.getDefault();
        // Convert to lower case
        String s1 = str.toLowerCase(loc);
        // Convert to Upper case
        String s2 = str.toUpperCase(loc);

        System.out.println("old = " + str);
        System.out.println("lowercase = " + s1);
        System.out.println("uppercase= " + s2);
    }
}

No comments:

Post a Comment