Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a littl...
How can I parse a pubDate from a RSS feed to a Date object in java. The format in the RSS feed: Sat, 24 Apr 2010 14:01:00 GMT What I have at the moment: DateFormat dateFormat = DateFormat.getInstance(); Date pubDate = dateFormat.parse(item.getPubDate().getText()); But this code throws an ParseException with the message Unparseable date
Is there a neat way of getting a Locale instance from its "programmatic name" as returned by Locale's toString() method? An obvious and ugly solution would be parsing the String and then constructing a new Locale instance according to that, but maybe there's a better way / ready solution for that? The need is that I want to store some locale specific settings in a SQL database, including Local...
The Java class java.util.Locale has a set of public static final fields for languages/countries for direct references to specific locales. Other locales can easily be used via the appropriate constructors. However, the selection of values seems rather arbitrary to me. The languages are (in the order in which they appear in the source): English, French, German, Italian, Japanese, Korean, Chine...
I have just installed jre7 and I'm surprised to see that my default locale is now en_US. With jre6 it was de_CH. What is different with jre7? Is the default locale no more the one of the Operating System? (btw, I'm using Windows7) Thx for your answer. Edit: I have seen the Locale for Category.FORMAT is the "old" one (de_CH). The Locale for Category.DISPLAY takes the language from the langua...
I want to have a List or Array of some sort, storing this information about each country: 2 letter code Country name such as Brazil Continent/region of the world such as Eastern Europe, North America, etc. I will classify each country into the region/continent manually (but if there exists a way to do this automatically, do let me know). This question is about how to store and access the c...
Are there any constants for language codes like "en" or "de" in java or in a java library? (Or is using the strings OK?) I know that something like Locale.COUNTRY-NAME.getLanguage() would work, but I am searching for something more streamlined like Locale.LANGUAGE-NAME
Here's the locale alphabet order: wikipedia Here's my code: public static void main(String[] args) { Locale loc = new Locale("sr","RS"); Collator col = Collator.getInstance(loc); col.setStrength(Collator.SECONDARY); List<String> slova = new ArrayList<String>(); slova.add("Austrija"); slova.add("Slovačka"); slova.add("Č"); slova.add("Đ"); slo...
I have different classes called English, Spanish, French, etc.: Class English{ String name = "English"; String alias = "ENG"; } Class French{ String name = "French"; String alias = "Fre"; } Similarly other language classes. And one more class called Language: Class Language{ String name = ""; String alias = ""; } Depending upon my requirements I want to cast Engl...
I am having all my resourcebundle values in table and formatted as per requirement.i have to change the languages in the website based on User selection in drop down in top of the page. If i use language code as en_US then its working fine. if i Use en-Us as Language Code then its not working. What might be the problem. Which is correct to follow?
import java.io.UnsupportedEncodingException; import java.util.Locale; public final class ForeignTextDemo { public static void main(String[] args) throws UnsupportedEncodingException { Locale locale = new Locale("TW"); System.out.println(locale.getDisplayLanguage(Locale.TRADITIONAL_CHINESE)); locale = new Locale("CN"); System.out.println(locale.getDisplayLan...
I find that I always find it useful to have a list of all Countries and their country codes. If someone provided it in multiple formats (eg: SQL, DDL, Xml, CSV, JSON, YAML...). I've found sites that attempt to sell a list of countries but that seems crazy to me. Is there an open source project that I'm overlooking? If there isn't does anyone else see any usefulness of starting a project that m...
How to get the name of the day from java sql.Timestamp object such as Monday, Tuesday?
When using toString(), Double adds commas (5143 is printed as 5,143). How to disable the commas?
Is Java String.hashcode() completely independent of Locale? In other words, if someone fiddles with the default Locale, are we 100% sure this is not going to impact the hash code? We know that such fiddling impacts toUpperCase() and toLowerCase().
In my android app I need to know which is the language of the phone in this format :fr (for francais), en (for english),etc.. How can I do this? I know that I can display language with this : Locale.getDefault().getDisplayLanguage() but the result is francais,english,... Can I obtain somehow the initials of languages?
I have been sneaking into some code written by professionals (not to mention on the SO).. I found people referencing often to the word locale ( for eg found some std::locale). Even some code in java refers to locale . So what is this locale and why do we actually need it? And is it necessary to use it ( I guess it is used for some portability issues)? I tried googling but everything just added ...
What is the correct way of knowing operating system language (locale) from java code? I have tried Locale.getDefault() System.getProperties("user.language") etc. but they are not correct nothing actually displays the "System Locale" which is available by the command "systeminfo" in windows. Please help.
That is, if I have "English (United States)" I'd like to get "en-US", or an appropriate java.util.Locale. It looks like the API is a one-way street, but perhaps I'm not looking in the right place. Thanks in advance.
I used following code, but it displays only 2 digit of ISO country name. For example, for "INDIA", it only display "IN". Can I show full name as "INDIA" ? String[] loc= Locale.getISOCountries(); for(int a=0;a<loc.length;a++) { System.out.println("ISO Contry "+a+":"+loc[a]); } I want full name of ISO country. Is it possible to get using this method?
I m using ResourceBundle method getBundle(Propertyfilename,Local.languagename) class which returns an object of ResourceBundle of the local rb = ResourceBundle.get Bundle("Locale Strings", Locale.ARABIC);-Not Supported How can i use this to support arabic,band english.
   /*
    * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  /*
   * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
   * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
   *
   * The original version of this source code and documentation
   * is copyrighted and owned by Taligent, Inc., a wholly-owned
   * subsidiary of IBM. These materials are provided under terms
   * of a License Agreement between Taligent and Sun. This technology
   * is protected by multiple US and International patents.
   *
   * This notice and attribution to Taligent may not be removed.
   * Taligent is a registered trademark of Taligent, Inc.
   *
   */
  
  package java.util;
  
  import java.io.*;
  import java.util.List;
A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture.

Create a Locale object using the constructors in this class:

 Locale(String language)
 Locale(String language, String country)
 Locale(String language, String country, String variant)
 
The language argument is a valid ISO Language Code. These codes are the lower-case, two-letter codes as defined by ISO-639. You can find a full list of these codes at a number of sites, such as:
http://www.loc.gov/standards/iso639-2/php/English_list.php

The country argument is a valid ISO Country Code. These codes are the upper-case, two-letter codes as defined by ISO-3166. You can find a full list of these codes at a number of sites, such as:
http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html

The variant argument is a vendor or browser-specific code. For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX. Where there are two variants, separate them with an underscore, and put the most important one first. For example, a Traditional Spanish collation might construct a locale with parameters for language, country and variant as: "es", "ES", "Traditional_WIN".

Because a Locale object is just an identifier for a region, no validity check is performed when you construct a Locale. If you want to see whether particular resources are available for the Locale you construct, you must query those resources. For example, ask the NumberFormat for the locales it supports using its getAvailableLocales method.
Note: When you ask for a resource for a particular locale, you get back the best available match, not necessarily precisely what you asked for. For more information, look at ResourceBundle.

The Locale class provides a number of convenient constants that you can use to create Locale objects for commonly used locales. For example, the following creates a Locale object for the United States:

 Locale.US
 

Once you've created a Locale you can query it for information about itself. Use getCountry to get the ISO Country Code and getLanguage to get the ISO Language Code. You can use getDisplayCountry to get the name of the country suitable for displaying to the user. Similarly, you can use getDisplayLanguage to get the name of the language suitable for displaying to the user. Interestingly, the getDisplayXXX methods are themselves locale-sensitive and have two versions: one that uses the default locale and one that uses the locale specified as an argument.

The Java Platform provides a number of classes that perform locale-sensitive operations. For example, the NumberFormat class formats numbers, currency, or percentages in a locale-sensitive manner. Classes such as NumberFormat have a number of convenience methods for creating a default object of that type. For example, the NumberFormat class provides these three convenience methods for creating a default NumberFormat object:

 NumberFormat.getInstance()
 NumberFormat.getCurrencyInstance()
 NumberFormat.getPercentInstance()
 
These methods have two variants; one with an explicit locale and one without; the latter using the default locale.
 NumberFormat.getInstance(myLocale)
 NumberFormat.getCurrencyInstance(myLocale)
 NumberFormat.getPercentInstance(myLocale)
 
A Locale is the mechanism for identifying the kind of object (NumberFormat) that you would like to get. The locale is just a mechanism for identifying objects, not a container for the objects themselves.

 
 
 public final class Locale implements CloneableSerializable {
 
     // cache to store singleton Locales
     private final static ConcurrentHashMap<StringLocalecache =
         new ConcurrentHashMap<StringLocale>(32);

    
Useful constant for language.
 
     static public final Locale ENGLISH = createSingleton("en__""en""");

    
Useful constant for language.
 
     static public final Locale FRENCH = createSingleton("fr__""fr""");

    
Useful constant for language.
 
     static public final Locale GERMAN = createSingleton("de__""de""");

    
Useful constant for language.
 
     static public final Locale ITALIAN = createSingleton("it__""it""");

    
Useful constant for language.
 
     static public final Locale JAPANESE = createSingleton("ja__""ja""");

    
Useful constant for language.
 
     static public final Locale KOREAN = createSingleton("ko__""ko""");

    
Useful constant for language.
 
     static public final Locale CHINESE = createSingleton("zh__""zh""");

    
Useful constant for language.
 
     static public final Locale SIMPLIFIED_CHINESE = createSingleton("zh_CN_""zh""CN");

    
Useful constant for language.
 
     static public final Locale TRADITIONAL_CHINESE = createSingleton("zh_TW_""zh""TW");

    
Useful constant for country.
 
     static public final Locale FRANCE = createSingleton("fr_FR_""fr""FR");

    
Useful constant for country.
 
     static public final Locale GERMANY = createSingleton("de_DE_""de""DE");

    
Useful constant for country.
 
     static public final Locale ITALY = createSingleton("it_IT_""it""IT");

    
Useful constant for country.
 
     static public final Locale JAPAN = createSingleton("ja_JP_""ja""JP");

    
Useful constant for country.
 
     static public final Locale KOREA = createSingleton("ko_KR_""ko""KR");

    
Useful constant for country.
 
     static public final Locale CHINA = ;

    
Useful constant for country.
 
     static public final Locale PRC = ;

    
Useful constant for country.
 
     static public final Locale TAIWAN = ;

    
Useful constant for country.
 
     static public final Locale UK = createSingleton("en_GB_""en""GB");

    
Useful constant for country.
 
     static public final Locale US = createSingleton("en_US_""en""US");

    
Useful constant for country.
 
     static public final Locale CANADA = createSingleton("en_CA_""en""CA");

    
Useful constant for country.
 
     static public final Locale CANADA_FRENCH = createSingleton("fr_CA_""fr""CA");

    
Useful constant for the root locale. The root locale is the locale whose language, country, and variant are empty ("") strings. This is regarded as the base locale of all locales, and is used as the language/country neutral locale for the locale sensitive operations.

Since:
1.6
 
     static public final Locale ROOT = createSingleton("__""""");

    
serialization ID
 
     static final long serialVersionUID = 9149081749638150636L;

    
Display types for retrieving localized names from the name providers.
 
     private static final int DISPLAY_LANGUAGE = 0;
     private static final int DISPLAY_COUNTRY  = 1;
     private static final int DISPLAY_VARIANT  = 2;

    
Construct a locale from language, country, variant. NOTE: ISO 639 is not a stable standard; some of the language codes it defines (specifically iw, ji, and in) have changed. This constructor accepts both the old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other API on Locale will return only the OLD codes.

Parameters:
language lowercase two-letter ISO-639 code.
country uppercase two-letter ISO-3166 code.
variant vendor and browser specific code. See class description.
Throws:
java.lang.NullPointerException thrown if any argument is null.
 
     public Locale(String languageString countryString variant) {
         this. = convertOldISOCodes(language);
         this. = toUpperCase(country).intern();
         this. = variant.intern();
     }

    
Construct a locale from language, country. NOTE: ISO 639 is not a stable standard; some of the language codes it defines (specifically iw, ji, and in) have changed. This constructor accepts both the old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other API on Locale will return only the OLD codes.

Parameters:
language lowercase two-letter ISO-639 code.
country uppercase two-letter ISO-3166 code.
Throws:
java.lang.NullPointerException thrown if either argument is null.
 
     public Locale(String languageString country) {
         this(languagecountry"");
     }

    
Construct a locale from a language code. NOTE: ISO 639 is not a stable standard; some of the language codes it defines (specifically iw, ji, and in) have changed. This constructor accepts both the old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other API on Locale will return only the OLD codes.

Parameters:
language lowercase two-letter ISO-639 code.
Throws:
java.lang.NullPointerException thrown if argument is null.
Since:
1.4
 
     public Locale(String language) {
         this(language"""");
     }

    
Constructs a Locale using language and country. This constructor assumes that language and contry are interned and it is invoked by createSingleton only. (flag is just for avoiding the conflict with the public constructors.
 
     private Locale(String languageString countryboolean flag) {
         this. = language;
         this. = country;
         this. = "";
     }

    
Creates a Locale instance with the given language and counry and puts the instance under the given key in the cache. This method must be called only when initializing the Locale constants.
 
     private static Locale createSingleton(String keyString languageString country) {
         Locale locale = new Locale(languagecountryfalse);
         .put(keylocale);
         return locale;
     }

    
Returns a Locale constructed from the given language, country and variant. If the same Locale instance is available in the cache, then that instance is returned. Otherwise, a new Locale instance is created and cached.

Parameters:
language lowercase two-letter ISO-639 code.
country uppercase two-letter ISO-3166 code.
variant vendor and browser specific code. See class description.
Returns:
the Locale instance requested
Throws:
java.lang.NullPointerException if any argument is null.
 
     static Locale getInstance(String languageString countryString variant) {
         if (language== null || country == null || variant == null) {
             throw new NullPointerException();
         }
 
         StringBuilder sb = new StringBuilder();
         sb.append(language).append('_').append(country).append('_').append(variant);
         String key = sb.toString();
         Locale locale = .get(key);
         if (locale == null) {
             locale = new Locale(languagecountryvariant);
             Locale l = .putIfAbsent(keylocale);
             if (l != null) {
                 locale = l;
             }
         }
         return locale;
     }

    
Gets the current value of the default locale for this instance of the Java Virtual Machine.

The Java Virtual Machine sets the default locale during startup based on the host environment. It is used by many locale-sensitive methods if no locale is explicitly specified. It can be changed using the setDefault method.

Returns:
the default locale for this instance of the Java Virtual Machine
 
     public static Locale getDefault() {
         // do not synchronize this method - see 4071298
         // it's OK if more than one default locale happens to be created
         if ( == null) {
             String languageregioncountryvariant;
             language = AccessController.doPrivileged(
                 new GetPropertyAction("user.language""en"));
             // for compatibility, check for old user.region property
             region = AccessController.doPrivileged(
                 new GetPropertyAction("user.region"));
             if (region != null) {
                 // region can be of form country, country_variant, or _variant
                 int i = region.indexOf('_');
                 if (i >= 0) {
                     country = region.substring(0, i);
                     variant = region.substring(i + 1);
                 } else {
                     country = region;
                     variant = "";
                 }
             } else {
                 country = AccessController.doPrivileged(
                     new GetPropertyAction("user.country"""));
                 variant = AccessController.doPrivileged(
                     new GetPropertyAction("user.variant"""));
             }
              = getInstance(languagecountryvariant);
         }
         return ;
     }

    
Sets the default locale for this instance of the Java Virtual Machine. This does not affect the host locale.

If there is a security manager, its checkPermission method is called with a PropertyPermission("user.language", "write") permission before the default locale is changed.

The Java Virtual Machine sets the default locale during startup based on the host environment. It is used by many locale-sensitive methods if no locale is explicitly specified.

Since changing the default locale may affect many different areas of functionality, this method should only be used if the caller is prepared to reinitialize locale-sensitive code running within the same Java Virtual Machine.

Parameters:
newLocale the new default locale
Throws:
java.lang.SecurityException if a security manager exists and its checkPermission method doesn't allow the operation.
java.lang.NullPointerException if newLocale is null
See also:
java.lang.SecurityManager.checkPermission(java.security.Permission)
PropertyPermission
 
     public static synchronized void setDefault(Locale newLocale) {
         if (newLocale == null)
             throw new NullPointerException("Can't set default locale to NULL");
 
         SecurityManager sm = System.getSecurityManager();
         if (sm != nullsm.checkPermission(new PropertyPermission
                         ("user.language""write"));
              = newLocale;
     }

    
Returns an array of all installed locales. The returned array represents the union of locales supported by the Java runtime environment and by installed LocaleServiceProvider implementations. It must contain at least a Locale instance equal to Locale.US.

Returns:
An array of installed locales.
 
     public static Locale[] getAvailableLocales() {
         return LocaleServiceProviderPool.getAllAvailableLocales();
     }

    
Returns a list of all 2-letter country codes defined in ISO 3166. Can be used to create Locales.
 
     public static String[] getISOCountries() {
         if ( == null) {
         }
         String[] result = new String[.];
         System.arraycopy(, 0, result, 0, .);
         return result;
     }

    
Returns a list of all 2-letter language codes defined in ISO 639. Can be used to create Locales. [NOTE: ISO 639 is not a stable standard-- some languages' codes have changed. The list this function returns includes both the new and the old codes for the languages whose codes have changed.]
 
     public static String[] getISOLanguages() {
         if ( == null) {
         }
         String[] result = new String[.];
         System.arraycopy(, 0, result, 0, .);
         return result;
     }
 
     private static final String[] getISO2Table(String table) {
         int len = table.length() / 5;
         String[] isoTable = new String[len];
         for (int i = 0, j = 0; i < leni++, j += 5) {
             isoTable[i] = table.substring(jj + 2);
         }
         return isoTable;
     }

    
Returns the language code for this locale, which will either be the empty string or a lowercase ISO 639 code.

NOTE: ISO 639 is not a stable standard-- some languages' codes have changed. Locale's constructor recognizes both the new and the old codes for the languages whose codes have changed, but this function always returns the old code. If you want to check for a specific language whose code has changed, don't do

 if (locale.getLanguage().equals("he"))
    ...
 
Instead, do
 if (locale.getLanguage().equals(new Locale("he", "", "").getLanguage()))
    ...

 
     public String getLanguage() {
         return ;
     }

    
Returns the country/region code for this locale, which will either be the empty string or an uppercase ISO 3166 2-letter code.

 
     public String getCountry() {
         return ;
     }

    
Returns the variant code for this locale.

 
     public String getVariant() {
         return ;
     }

    
Getter for the programmatic name of the entire locale, with the language, country and variant separated by underbars. Language is always lower case, and country is always upper case. If the language is missing, the string will begin with an underbar. If both the language and country fields are missing, this function will return the empty string, even if the variant field is filled in (you can't have a locale with just a variant-- the variant must accompany a valid language or country code). Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"

 
     public final String toString() {
         boolean l = .length() != 0;
         boolean c = .length() != 0;
         boolean v = .length() != 0;
         StringBuilder result = new StringBuilder();
         if (c||(l&&v)) {
             result.append('_').append(); // This may just append '_'
         }
         if (v&&(l||c)) {
             result.append('_').append();
         }
         return result.toString();
     }

    
Returns a three-letter abbreviation for this locale's language. If the locale doesn't specify a language, this will be the empty string. Otherwise, this will be a lowercase ISO 639-2/T language code. The ISO 639-2 language codes can be found on-line at http://www.loc.gov/standards/iso639-2/englangn.html.

Throws:
MissingResourceException Throws MissingResourceException if the three-letter language abbreviation is not available for this locale.
 
     public String getISO3Language() throws MissingResourceException {
         String language3 = getISO3Code(.);
         if (language3 == null) {
             throw new MissingResourceException("Couldn't find 3-letter language code for "
                     + "FormatData_" + toString(), "ShortLanguage");
         }
         return language3;
     }

    
Returns a three-letter abbreviation for this locale's country. If the locale doesn't specify a country, this will be the empty string. Otherwise, this will be an uppercase ISO 3166 3-letter country code. The ISO 3166-2 country codes can be found on-line at http://www.davros.org/misc/iso3166.txt.

Throws:
MissingResourceException Throws MissingResourceException if the three-letter country abbreviation is not available for this locale.
 
     public String getISO3Country() throws MissingResourceException {
         String country3 = getISO3Code(.);
         if (country3 == null) {
             throw new MissingResourceException("Couldn't find 3-letter country code for "
                     + "FormatData_" + toString(), "ShortCountry");
         }
         return country3;
     }
 
     private static final String getISO3Code(String iso2CodeString table) {
         int codeLength = iso2Code.length();
         if (codeLength == 0) {
             return "";
         }
 
         int tableLength = table.length();
         int index = tableLength;
         if (codeLength == 2) {
             char c1 = iso2Code.charAt(0);
             char c2 = iso2Code.charAt(1);
             for (index = 0; index < tableLengthindex += 5) {
                 if (table.charAt(index) == c1
                     && table.charAt(index + 1) == c2) {
                     break;
                 }
             }
         }
         return index < tableLength ? table.substring(index + 2, index + 5) : null;
     }

    
Returns a name for the locale's language that is appropriate for display to the user. If possible, the name returned will be localized for the default locale. For example, if the locale is fr_FR and the default locale is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and the default locale is fr_FR, getDisplayLanguage() will return "anglais". If the name returned cannot be localized for the default locale, (say, we don't have a Japanese name for Croatian), this function falls back on the English name, and uses the ISO code as a last-resort value. If the locale doesn't specify a language, this function returns the empty string.
 
     public final String getDisplayLanguage() {
         return getDisplayLanguage(getDefault());
     }

    
Returns a name for the locale's language that is appropriate for display to the user. If possible, the name returned will be localized according to inLocale. For example, if the locale is fr_FR and inLocale is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and inLocale is fr_FR, getDisplayLanguage() will return "anglais". If the name returned cannot be localized according to inLocale, (say, we don't have a Japanese name for Croatian), this function falls back on the English name, and finally on the ISO code as a last-resort value. If the locale doesn't specify a language, this function returns the empty string.

Throws:
java.lang.NullPointerException if inLocale is null
 
     public String getDisplayLanguage(Locale inLocale) {
         return getDisplayString(inLocale);
     }

    
Returns a name for the locale's country that is appropriate for display to the user. If possible, the name returned will be localized for the default locale. For example, if the locale is fr_FR and the default locale is en_US, getDisplayCountry() will return "France"; if the locale is en_US and the default locale is fr_FR, getDisplayCountry() will return "Etats-Unis". If the name returned cannot be localized for the default locale, (say, we don't have a Japanese name for Croatia), this function falls back on the English name, and uses the ISO code as a last-resort value. If the locale doesn't specify a country, this function returns the empty string.
 
     public final String getDisplayCountry() {
         return getDisplayCountry(getDefault());
     }

    
Returns a name for the locale's country that is appropriate for display to the user. If possible, the name returned will be localized according to inLocale. For example, if the locale is fr_FR and inLocale is en_US, getDisplayCountry() will return "France"; if the locale is en_US and inLocale is fr_FR, getDisplayCountry() will return "Etats-Unis". If the name returned cannot be localized according to inLocale. (say, we don't have a Japanese name for Croatia), this function falls back on the English name, and finally on the ISO code as a last-resort value. If the locale doesn't specify a country, this function returns the empty string.

Throws:
java.lang.NullPointerException if inLocale is null
 
     public String getDisplayCountry(Locale inLocale) {
         return getDisplayString(inLocale);
     }
 
     private String getDisplayString(String codeLocale inLocaleint type) {
         if (code.length() == 0) {
             return "";
         }
 
         if (inLocale == null) {
             throw new NullPointerException();
         }
 
         try {
             OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
             String key = (type ==  ? "%%"+code : code);
             String result = null;
 
             // Check whether a provider can provide an implementation that's closer
             // to the requested locale than what the Java runtime itself can provide.
             LocaleServiceProviderPool pool =
                 LocaleServiceProviderPool.getPool(LocaleNameProvider.class);
             if (pool.hasProviders()) {
                 result = pool.getLocalizedObject(
                                     .,
                                     inLocalebundlekey,
                                     typecode);
             }
 
             if (result == null) {
                 result = bundle.getString(key);
             }
 
             if (result != null) {
                 return result;
             }
         }
         catch (Exception e) {
             // just fall through
         }
         return code;
     }

    
Returns a name for the locale's variant code that is appropriate for display to the user. If possible, the name will be localized for the default locale. If the locale doesn't specify a variant code, this function returns the empty string.
 
     public final String getDisplayVariant() {
         return getDisplayVariant(getDefault());
     }

    
Returns a name for the locale's variant code that is appropriate for display to the user. If possible, the name will be localized for inLocale. If the locale doesn't specify a variant code, this function returns the empty string.

Throws:
java.lang.NullPointerException if inLocale is null
 
     public String getDisplayVariant(Locale inLocale) {
         if (.length() == 0)
             return "";
 
         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
 
         String names[] = getDisplayVariantArray(bundleinLocale);
 
         // Get the localized patterns for formatting a list, and use
         // them to format the list.
         String listPattern = null;
         String listCompositionPattern = null;
         try {
             listPattern = bundle.getString("ListPattern");
             listCompositionPattern = bundle.getString("ListCompositionPattern");
         } catch (MissingResourceException e) {
         }
         return formatList(nameslistPatternlistCompositionPattern);
     }

    
Returns a name for the locale that is appropriate for display to the user. This will be the values returned by getDisplayLanguage(), getDisplayCountry(), and getDisplayVariant() assembled into a single string. The display name will have one of the following forms:

language (country, variant)

language (country)

language (variant)

country (variant)

language

country

variant

depending on which fields are specified in the locale. If the language, country, and variant fields are all empty, this function returns the empty string.
 
     public final String getDisplayName() {
         return getDisplayName(getDefault());
     }

    
Returns a name for the locale that is appropriate for display to the user. This will be the values returned by getDisplayLanguage(), getDisplayCountry(), and getDisplayVariant() assembled into a single string. The display name will have one of the following forms:

language (country, variant)

language (country)

language (variant)

country (variant)

language

country

variant

depending on which fields are specified in the locale. If the language, country, and variant fields are all empty, this function returns the empty string.

Throws:
java.lang.NullPointerException if inLocale is null
 
     public String getDisplayName(Locale inLocale) {
         OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
 
         String languageName = getDisplayLanguage(inLocale);
         String countryName = getDisplayCountry(inLocale);
         String[] variantNames = getDisplayVariantArray(bundleinLocale);
 
         // Get the localized patterns for formatting a display name.
         String displayNamePattern = null;
         String listPattern = null;
         String listCompositionPattern = null;
         try {
             displayNamePattern = bundle.getString("DisplayNamePattern");
             listPattern = bundle.getString("ListPattern");
             listCompositionPattern = bundle.getString("ListCompositionPattern");
         } catch (MissingResourceException e) {
         }
 
         // The display name consists of a main name, followed by qualifiers.
         // Typically, the format is "MainName (Qualifier, Qualifier)" but this
         // depends on what pattern is stored in the display locale.
         String   mainName       = null;
         String[] qualifierNames = null;
 
         // The main name is the language, or if there is no language, the country.
         // If there is neither language nor country (an anomalous situation) then
         // the display name is simply the variant's display name.
         if (languageName.length() != 0) {
             mainName = languageName;
             if (countryName.length() != 0) {
                 qualifierNames = new String[variantNames.length + 1];
                 System.arraycopy(variantNames, 0, qualifierNames, 1, variantNames.length);
                 qualifierNames[0] = countryName;
             }
             else qualifierNames = variantNames;
         }
         else if (countryName.length() != 0) {
             mainName = countryName;
             qualifierNames = variantNames;
         }
         else {
             return formatList(variantNameslistPatternlistCompositionPattern);
         }
 
         // Create an array whose first element is the number of remaining
         // elements.  This serves as a selector into a ChoiceFormat pattern from
         // the resource.  The second and third elements are the main name and
         // the qualifier; if there are no qualifiers, the third element is
         // unused by the format pattern.
         Object[] displayNames = {
             new Integer(qualifierNames.length != 0 ? 2 : 1),
             mainName,
             // We could also just call formatList() and have it handle the empty
             // list case, but this is more efficient, and we want it to be
             // efficient since all the language-only locales will not have any
             // qualifiers.
             qualifierNames.length != 0 ? formatList(qualifierNameslistPatternlistCompositionPattern) : null
         };
 
         if (displayNamePattern != null) {
             return new MessageFormat(displayNamePattern).format(displayNames);
         }
         else {
             // If we cannot get the message format pattern, then we use a simple
             // hard-coded pattern.  This should not occur in practice unless the
             // installation is missing some core files (FormatData etc.).
             StringBuilder result = new StringBuilder();
             result.append((String)displayNames[1]);
             if (displayNames.length > 2) {
                 result.append(" (");
                 result.append((String)displayNames[2]);
                 result.append(')');
             }
             return result.toString();
         }
     }

    
Overrides Cloneable
 
     public Object clone()
     {
         try {
             Locale that = (Locale)super.clone();
             return that;
         } catch (CloneNotSupportedException e) {
             throw new InternalError();
         }
     }

    
Override hashCode. Since Locales are often used in hashtables, caches the value for speed.
 
     public int hashCode() {
         int hc = ;
         if (hc == 0) {
             hc = (.hashCode() << 8) ^ .hashCode() ^ (.hashCode() << 4);
              = hc;
         }
         return hc;
     }
 
     // Overrides
 
    
Returns true if this Locale is equal to another object. A Locale is deemed equal to another Locale with identical language, country, and variant, and unequal to all other objects.

Returns:
true if this Locale is equal to the specified object.
 
 
     public boolean equals(Object obj) {
         if (this == obj)                      // quick check
             return true;
         if (!(obj instanceof Locale))
             return false;
         Locale other = (Localeobj;
         return  == other.language
             &&  == other.country
             &&  == other.variant;
     }
 
     // ================= privates =====================================
 
     // XXX instance and class variables. For now keep these separate, since it is
     // faster to match. Later, make into single string.
 
    

See also:
getLanguage()
Serial:
 
     private final String language;

    

See also:
getCountry()
Serial:
 
     private final String country;

    

See also:
getVariant()
Serial:
 
     private final String variant;

    
Placeholder for the object's hash code. Always -1.

Serial:
 
     private volatile int hashcode = -1;        // lazy evaluate
 
    
Calculated hashcode to fix 4518797.
 
     private transient volatile int hashCodeValue = 0;
 
     private static Locale defaultLocale = null;

    
Return an array of the display names of the variant.

Parameters:
bundle the ResourceBundle to use to get the display names
Returns:
an array of display names, possible of zero length.
 
     private String[] getDisplayVariantArray(OpenListResourceBundle bundleLocale inLocale) {
         // Split the variant name into tokens separated by '_'.
         StringTokenizer tokenizer = new StringTokenizer("_");
         String[] names = new String[tokenizer.countTokens()];
 
         // For each variant token, lookup the display name.  If
         // not found, use the variant name itself.
         for (int i=0; i<names.length; ++i) {
             names[i] = getDisplayString(tokenizer.nextToken(),
                                 inLocale);
         }
 
         return names;
     }

    
Format a list using given pattern strings. If either of the patterns is null, then a the list is formatted by concatenation with the delimiter ','.

Parameters:
stringList the list of strings to be formatted.
listPattern should create a MessageFormat taking 0-3 arguments and formatting them into a list.
listCompositionPattern should take 2 arguments and is used by composeList.
Returns:
a string representing the list.
    private static String formatList(String[] stringListString listPatternString listCompositionPattern) {
        // If we have no list patterns, compose the list in a simple,
        // non-localized way.
        if (listPattern == null || listCompositionPattern == null) {
            StringBuffer result = new StringBuffer();
            for (int i=0; i<stringList.length; ++i) {
                if (i>0) result.append(',');
                result.append(stringList[i]);
            }
            return result.toString();
        }
        // Compose the list down to three elements if necessary
        if (stringList.length > 3) {
            MessageFormat format = new MessageFormat(listCompositionPattern);
            stringList = composeList(formatstringList);
        }
        // Rebuild the argument list with the list length as the first element
        Object[] args = new Object[stringList.length + 1];
        System.arraycopy(stringList, 0, args, 1, stringList.length);
        args[0] = new Integer(stringList.length);
        // Format it using the pattern in the resource
        MessageFormat format = new MessageFormat(listPattern);
        return format.format(args);
    }

    
Given a list of strings, return a list shortened to three elements. Shorten it by applying the given format to the first two elements recursively.

Parameters:
format a format which takes two arguments
list a list of strings
Returns:
if the list is three elements or shorter, the same list; otherwise, a new list of three elements.
    private static String[] composeList(MessageFormat formatString[] list) {
        if (list.length <= 3) return list;
        // Use the given format to compose the first two elements into one
        String[] listItems = { list[0], list[1] };
        String newItem = format.format(listItems);
        // Form a new list one element shorter
        String[] newList = new String[list.length-1];
        System.arraycopy(list, 2, newList, 1, newList.length-1);
        newList[0] = newItem;
        // Recurse
        return composeList(formatnewList);
    }

    
Replace the deserialized Locale object with a newly created object. Newer language codes are replaced with older ISO codes. The country and variant codes are replaced with internalized String copies.
    private Object readResolve() throws java.io.ObjectStreamException {
        return getInstance();
    }
    private static volatile String[] isoLanguages = null;
    private static volatile String[] isoCountries = null;
    /*
     * Locale needs its own, locale insensitive version of toLowerCase to
     * avoid circularity problems between Locale and String.
     * The most straightforward algorithm is used. Look at optimizations later.
     */
    private String toLowerCase(String str) {
        char[] buf = new char[str.length()];
        for (int i = 0; i < buf.lengthi++) {
            buf[i] = Character.toLowerCase(str.charAt(i));
        }
        return new Stringbuf );
    }
    /*
     * Locale needs its own, locale insensitive version of toUpperCase to
     * avoid circularity problems between Locale and String.
     * The most straightforward algorithm is used. Look at optimizations later.
     */
    private String toUpperCase(String str) {
        char[] buf = new char[str.length()];
        for (int i = 0; i < buf.lengthi++) {
            buf[i] = Character.toUpperCase(str.charAt(i));
        }
        return new Stringbuf );
    }
    private String convertOldISOCodes(String language) {
        // we accept both the old and the new ISO codes for the languages whose ISO
        // codes have changed, but we always store the OLD code, for backward compatibility
        language = toLowerCase(language).intern();
        if (language == "he") {
            return "iw";
        } else if (language == "yi") {
            return "ji";
        } else if (language == "id") {
            return "in";
        } else {
            return language;
        }
    }

    
Obtains a localized locale names from a LocaleNameProvider implementation.
    private static class LocaleNameGetter
        private static final LocaleNameGetter INSTANCE = new LocaleNameGetter();
        public String getObject(LocaleNameProvider localeNameProvider,
                                Locale locale,
                                String key,
                                Object... params) {
            assert params.length == 2;
            int type = (Integer)params[0];
            String code = (String)params[1];
            switch(type) {
            case :
                return localeNameProvider.getDisplayLanguage(codelocale);
            case :
                return localeNameProvider.getDisplayCountry(codelocale);
            case :
                return localeNameProvider.getDisplayVariant(codelocale);
            default:
                assert false// shouldn't happen
            }
            return null;
        }
    }
New to GrepCode? Check out our FAQ X