Internationalization(I18N) in Java


Internationalization (I18N) is the process of designing and developing software applications that can be adapted to various languages and regions without any changes to the source code. Java provides extensive support for I18N through its core libraries and APIs.

Here are some of the ways to implement I18N in Java:

  • Resource Bundles: Resource bundles are a set of properties files that contain key-value pairs for different languages. Java provides the ResourceBundle class to load and access these properties files. The ResourceBundle class uses the default locale of the system to load the appropriate properties file. For example, if the default locale is set to "en_US", the ResourceBundle will load the properties file with the name "messages_en_US.properties". Here's an example of how to use ResourceBundle:
ResourceBundle bundle = ResourceBundle.getBundle("messages");
String message = bundle.getString("greeting");
System.out.println(message);
  • MessageFormat: MessageFormat is a class in Java that allows you to format messages with placeholders for variables. This is useful for languages that have different sentence structures or word orders. Here's an example:
String pattern = "Hello {0}, your balance is {1,number,currency}.";
Object[] arguments = {"John", 1234.56};
String message = MessageFormat.format(pattern, arguments);
System.out.println(message);
  • DateFormat: DateFormat is a class in Java that allows you to format dates and times according to the user's locale. Here's an example:
Date date = new Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
String message = df.format(date);
System.out.println(message);
  • NumberFormat: NumberFormat is a class in Java that allows you to format numbers according to the user's locale. Here's an example:
double number = 1234.56;
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
String message = nf.format(number);
System.out.println(message);
  • Locale: Locale is a class in Java that represents a specific language and region. You can use the Locale class to set the default locale of your application or to load specific resource bundles. Here's an example:
Locale.setDefault(Locale.US);
ResourceBundle bundle = ResourceBundle.getBundle("messages");
String message = bundle.getString("greeting");
System.out.println(message);

These are just a few examples of how to implement I18N in Java. There are many other classes and APIs available in Java for I18N, such as Collator, TimeZone, and Calendar. It's important to design your application with I18N in mind from the beginning to make it easier to adapt to different languages and regions in the future.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.