Webucator Blog

Saying “Hello World!” in Your Language using Java

The first two W’s in WWW stands for “World Wide,” and that infers many languages, dialects and character sets Consider the following “HelloWorld” application:

public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

The application is not very useful if it’s used in Germany. We could add logic to distinguish a language and add the string literal to our code, but that would become a maintenance nightmare if the list of languages grows as well as requiring a lot of recompiling with each addition. Java provides the Locale class that can be used to both problems:

import java.util.*;
public class InternationalHello {
	static public void main(String[] args) {
		String language = "";
		String country = "";
		if (args.length == 2) {
			language = new String(args[0]);
			country = new String(args[1]);
		}
		Locale currentLocale = new Locale(language, country);
		ResourceBundle messages =
			ResourceBundle.getBundle("MessagesBundle",
				currentLocale);
		System.out.println(messages.getString("hello"));
    }
}

“MessagesBundle” references a MessagesBundle*.properties file that contains the strings to be displayed. The following sample files and their contents:

MessagesBundle.properties (the default)

	hello = Anyone Out There

MessagesBundle_en_US.properties

	Hello=HelloWorld

MessagesBundle_de_DE.properties

	hello = Hallo Welt

MessagesBundle_fr_FR.properties

	hello = Bonjour Monde

Run the program using the following:

Java InternationalHello

The output will be:

Anyone Out There

When the program receives no arguments it will use MessagesBundle.properties as the default bundle.

Try:

Java InternationalHello de DE

The output is:

Hallo Welt

These arguments are used to identify the dialect and language. They are used to identify MessagesBundle_de_DE.properties as the bundle. Try using “fr FR” and “us EN”.

More and more languages can be added simply by adding a MessagesBundle*.properties files and the code doesn’t need to be recompiled. You gone “World Wide”.

Internationalization techniques are covered in our JSP, Spring MVC, JSTL and Struts classes.