Skip to content

Instantly share code, notes, and snippets.

@gkhays
Last active January 17, 2018 22:55
Show Gist options
  • Save gkhays/7a732f81eca8daf60cab7e6d48bfe2c0 to your computer and use it in GitHub Desktop.
Save gkhays/7a732f81eca8daf60cab7e6d48bfe2c0 to your computer and use it in GitHub Desktop.
Java string formatting

String.format

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

See String.format method.

Format String Syntax

MessageFormat

Alternatively use MessageFormat (java.text.MessageFormat).

The first example uses the static method MessageFormat.format, which internally creates a MessageFormat for one-time use:

 int planet = 7;
 String event = "a disturbance in the Force";

 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     planet, new Date(), event);

The output is:

 At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.

The following example creates a MessageFormat instance that can be used repeatedly:

 int fileCount = 1273;
 String diskName = "MyDisk";
 Object[] testArgs = {new Long(fileCount), diskName};

 MessageFormat form = new MessageFormat(
     "The disk \"{1}\" contains {0} file(s).");

 System.out.println(form.format(testArgs));

The output with different values for fileCount:

 The disk "MyDisk" contains 0 file(s).
 The disk "MyDisk" contains 1 file(s).
 The disk "MyDisk" contains 1,273 file(s).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment