Skip to content

MessageFormat

Pluralizing messages with Java MessageFormat and ChoiceFormat, with example outputs.

1 min read

Code snippet

import java.text.MessageFormat;
import java.util.logging.Logger;
import static java.util.logging.Level.INFO;
public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
String pattern = "You passed{0,choice,0# no |1# one |1< {0} }argument{0,choice,0#|1<s}";
String message = MessageFormat.format(pattern, args.length);
logger.log(INFO, message);
}
}

Understanding the code snippet

{0,choice,0# no |1# one |1< {0} }: This part is a ChoiceFormat that behaves based on the value of {0} (i.e., the number of arguments):

  • 0# no → if 0, print no
  • 1# one → if 1, print one
  • 1< {0} → if more than 1, print the actual number (e.g., 2, 3, etc.)

argument{0,choice,0#|1<s}: This part formats the word argument to add “s” only if {0} is not 0 or 1 (i.e., plural form).

  • 0# → nothing
  • 1# → nothing
  • 1< → adds “s”

Example outputs:

args.length Output
0 You passed no argument
1 You passed one argument
2 You passed 2 arguments
5 You passed 5 arguments

Related articles

3 min read

Jakarta

Jakarta EE namespaces, project settings and what changed in Jakarta EE 10 and 11.

  • Java & Jakarta EE
8 min read

JSF

Jakarta Faces (JSF) notes: WebSocket push, scopes, events, Ajax, security and cross-field validation.

  • Java & Jakarta EE
  • Web & Frontend
2 min read

Jasper Reports

JasperReports tips: internationalization, pagination, split types and floating elements.

  • Java & Jakarta EE

Type to search the whole site.