Java i18n Internationalization Example

Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes.

Sometimes I was wondering term internationalization is abbreviated as i18n, Why? and Found reason is   there are 18 letters between the first "i" and the last "n." :)

Why to use i18n and Benifits of i18n :
  1. Support for new languages does not require recompilation as stored in Properties Files.
  2. Can be localized quicklyby setting Local as per Language and country
  3. Instead of hard coding Textual elemtns(GUI labels,status message,Error message. they are stored outside and retrieved dynamically.
  4. By small additional of data(properties file of different landuage) , same code can be run WorldWide.
  5. Culturally dependent data, like dates and currencies, appear in formats that line up with user's region and language
Steps to create i18n Example : 

1. Create Properties Files and define key-value pair for "text" : "value in Specific Language"
    Ex. MessagesBundle_de_DE.properties
          MessagesBundle_en_US.properties
          MessagesBundle_fr_FR.properties

         MessagesBundle_de_DE.properties looks like as 
         greetings = Hallo.
         farewell = Tschüß.
         inquiry = Wie geht's?

2. Define Locale
    Ex. Locale currentLocale= new Locale("en", "US");
 
3. Create Resource Bundle
ResourceBundle messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);

4. Retrieve Text from Resource Bundle
Ex. messages.getString("greetings")


Java i18n Internalization Program : 

package com.anuj.utils;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 *
 * @author Anuj Patel
 */
public class i18nExample {

    public static void main(String[] args) {
        Locale currentLocale;
        ResourceBundle messages;
        String language = "de"; //en,de,fr
        String country = "DE"; //US,DE,FR

        currentLocale = new Locale(language, country);

        messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);

        System.out.println(messages.getString("greetings"));
        System.out.println(messages.getString("inquiry"));
        System.out.println(messages.getString("farewell"));
    }
}
Output :
Hallo.
Wie geht's?
Tschüß.


No comments:

Post a Comment