MessageFormat messageFmt = new MessageFormat("Temperature is {0} degrees Celsius."); Locale locale = new Locale("fr", "FR"); messageFmt.setLocale(locale); // set locale to French (France) System.out.println(messageFmt.format(new Object[] {25.5}));
Temperature is 25,5 degrés Celsius.
MessageFormat messageFmt = new MessageFormat("At {0,time} on {0,date}, there was {1} on planet {2,number,integer}."); Locale locale = new Locale("en", "US"); messageFmt.setLocale(locale); // set locale to English (United States) Object[] arguments = { new Date(), "a disturbance in the Force", 7 }; System.out.println(messageFmt.format(arguments));
At 2:11:46 PM on Nov 8, 2021, there was a disturbance in the Force on planet 7.In this example, the setLocale() method is used to set the locale to English (United States). The MessageFormat is then used to format a message that contains placeholders for a date, a string, and an integer. The format() method is called to perform the formatting, with an array of objects passed as arguments. In summary, the java.text.MessageFormat class provides functionality to format strings with placeholders for variables. The setLocale() method can be used to set the locale for the default formatting conventions used by this MessageFormat. The MessageFormat class is part of the 'java.text' package in the Java standard library.