Getting started with Java LanguageInheritanceStreamsExceptions and exception handlingCollectionsLambda ExpressionsGenericsFile I/OArraysInterfacesMapsStringsInputStreams and OutputStreamsDefault MethodsClasses and ObjectsBasic Control StructuresConcurrent Programming (Threads)Console I/OSingletonsVisibility (controlling access to members of a class)Regular ExpressionsAutoboxingDocumenting Java CodeExecutor, ExecutorService and Thread poolsObject Class Methods and ConstructorJAXBPrimitive Data TypesNetworkingOptionalEnumsHttpURLConnectionAnnotationsAudioDate ClassCalendar and its SubclassesNashorn JavaScript engineJava Native InterfaceRemote Method Invocation (RMI)Iterator and IterableOperatorsAssertingScannerProperties ClassPreferencesReflection APIConstructorsByteBufferSerializationJSON in JavaRandom Number GenerationRecursionPolymorphismStringBuilderReference Data TypesBit ManipulationJava AgentsEncapsulationType ConversionBigIntegerBigDecimalRSA EncryptionVarargs (Variable Argument)ThreadLocalLogging (java.util.logging)Using the static keywordDisassembling and DecompilingResources (on classpath)log4j / log4j2JVM FlagsOracle Official Code StandardCharacter encodingJava Memory ManagementImmutable ObjectsObject CloningAlternative CollectionsListsBufferedWriterLocalTimeSetsComparable and ComparatorJVM Tool InterfaceNested and Inner ClassesApache Commons LangGetters and SettersThe ClasspathBytecode ModificationXML Parsing using the JAXP APIsReference TypesLocalization and InternationalizationJAX-WSXML XPath EvaluationJava Performance TuningParallel programming with Fork/Join frameworkCommon Java PitfallsNon-Access ModifiersJava Compiler - 'javac'XJCProcessInstalling Java (Standard Edition)Command line Argument ProcessingDates and Time (java.time.*)Fluent InterfaceXOM - XML Object ModelJust in Time (JIT) compilerFTP (File Transfer Protocol)Java Native AccessModulesJava Pitfalls - Exception usageJava Pitfalls - Language syntaxServiceLoaderClassloadersObject ReferencesJava Pitfalls - Performance IssuesCreating Images ProgrammaticallyAppletsNIO - NetworkingNew File I/OSecure objectsJava Pitfalls - Threads and ConcurrencySplitting a string into fixed length partsJava Pitfalls - Nulls and NullPointerExceptionSecurityManagerJNDIsuper keywordThe java.util.Objects ClassThe Java Command - 'java' and 'javaw'Atomic TypesJava Floating Point OperationsConverting to and from Stringssun.misc.UnsafeJava Memory ModelJava deploymentJava plugin system implementationsQueues and DequesRuntime CommandsNumberFormatSecurity & CryptographyJava Virtual Machine (JVM)Unit TestingJavaBeanExpressionsLiteralsJava SE 8 FeaturesJava SE 7 FeaturesPackagesCurrency and MoneyConcurrent CollectionsUsing ThreadPoolExecutor in MultiThreaded applications.Java Editions, Versions, Releases and DistributionsDynamic Method DispatchJMXSecurity & CryptographyGenerating Java CodeJShellBenchmarksCollection Factory MethodsMulti-Release JAR FilesStack-Walking APITreeMap and TreeSetSocketsJava SocketsUsing Other Scripting Languages in JavaFunctional InterfacesList vs SET2D Graphics in JavaClass - Java ReflectionDequeue InterfaceEnum MapEnumSet classLocal Inner ClassJava Print ServiceImmutable ClassString TokenizerFileUpload to AWSAppDynamics and TIBCO BusinessWorks Instrumentation for Easy IntegrationReaders and WritersHashtableEnum starting with numberSortedMapWeakHashMapLinkedHashMapStringBufferChoosing CollectionsC++ ComparisonCompletableFuture

Localization and Internationalization

Other topics

Remarks:

Java comes with a powerful and flexible mechanism for localizing your applications, but it's also easy to misuse and wind up with a program that disregards or mangles the user's locale, and therefore how they expect your program to behave.

Your users will expect to see data localized to the formats they're used to, and attempting to support this manually is a fools errand. Here is just a small example of the different ways users expect to see content you might assume is "always" displayed a certain way:

DatesNumbersLocal CurrencyForeign CurrencyDistances
Brazil
China
Egypt
Mexico20/3/161.234,56$1,000.501,000.50 USD
UK20/3/161,234.56£1,000.50100 km
USA3/20/161,234.56$1,000.501,000.50 MXN60 mi

General Resources

Java Resources

Automatically formatted Dates using "locale"

SimpleDateFormatter is great in a pinch, but like the name suggests it doesn't scale well.

If you hard-code "MM/dd/yyyy" all over your application your international users won't be happy.

Let Java do the work for you

Use the static methods in DateFormat to retrieve the right formatting for your user. For a desktop application (where you'll rely on the default locale), simply call:

String localizedDate = DateFormat.getDateInstance(style).format(date);

Where style is one of the formatting constants (FULL, LONG, MEDIUM, SHORT, etc.) specified in DateFormat.

For a server-side application where the user specifies their locale as part of the request, you should pass it explicitly to getDateInstance() instead:

String localizedDate =
    DateFormat.getDateInstance(style, request.getLocale()).format(date);

String Comparison

Compare two Strings ignoring case:

"School".equalsIgnoreCase("school"); // true

Don't use

text1.toLowerCase().equals(text2.toLowerCase());

Languages have different rules for converting upper and lower case. A 'I' would be converted to 'i' in English. But in Turkish a 'I' becomes a 'ı'. If you have to use toLowerCase() use the overload which expects a Locale: String.toLowerCase(Locale).

Comparing two Strings ignoring minor differences:

Collator collator = Collator.getInstance(Locale.GERMAN);
collator.setStrength(Collator.PRIMARY);
collator.equals("Gärten", "gaerten"); // returns true

Sort Strings respecting natural language order, ignoring case (use collation key to:

String[] texts = new String[] {"Birne", "äther", "Apfel"};
Collator collator = Collator.getInstance(Locale.GERMAN);
collator.setStrength(Collator.SECONDARY); // ignore case
Arrays.sort(texts, collator::compare); // will return {"Apfel", "äther", "Birne"}

Locale

The java.util.Locale class is used to represent a "geographical, political or cultural" region to localize a given text, number, date or operation to. A Locale object may thus contain a country, region, language, and also a variant of a language, for instance a dialect spoken in a certain region of a country, or spoken in a different country than the country from which the language originates.

The Locale instance is handed to components that need to localize their actions, whether it is converting the input, output, or just need it for internal operations. The Locale class cannot do any internationalization or localization by itself

Language

The language must be an ISO 639 2 or 3 character language code, or a registered language subtag of up to 8 characters. In case a language has both a 2 and 3 character language code, use the 2 character code. A full list of language codes can be found in the IANA Language Subtag Registry.

Language codes are case insensitive, but the Locale class always use lowercase versions of the language codes

Creating a Locale

Creating a java.util.Locale instance can be done in four different ways:

Locale constants
Locale constructors
Locale.Builder class
Locale.forLanguageTag factory method 

Java ResourceBundle

You create a ResourceBundle instance like this:

Locale locale = new Locale("en", "US");
ResourceBundle labels = ResourceBundle.getBundle("i18n.properties");
System.out.println(labels.getString("message"));

Consider I have a property file i18n.properties:

message=This is locale

Output:

This is locale

Setting Locale

If you want to reproduce the state using other languages, you can use setDefault() method. Its usage:

 setDefault(Locale.JAPANESE); //Set Japanese

Contributors

Topic Id: 4086

Example Ids: 14228,14278,17951

This site is not affiliated with any of the contributors.