Topics Index

More Utility Classes > Formatter >
Siva Nookala - 06 Oct 2016
Formatting strings and characters is the simplest part of formatting. We can quickly look at an example to see how it works.

Format String Character Demo
import java.util.*;

class FormatStringCharacterDemo
    public static void main(String arg[])
        StringBuilder customOutput = new StringBuilder();
        Formatter f = new Formatter(customOutput); // LINE A
        f.format("|%s|%n", "Learn");
        f.format("|%5s|%n", "Java"); // LINE B
        f.format("|%-5s|%n", "With"); // LINE C
        f.format("|%campu%c|", 'C', 's');
        f.close(); // LINE D

| Java|
|With |


Firstly observe that we changed the way the Formatter is created using our own customOutput, this causes all the formatted output to be written to the passed StringBuilder.

This program demonstrates how we can use the '%s' format specifier for formatting the strings.

  • In the basic form '%s', it will simply print the string as is.
  • If we specify the number like '%5s', then it will ensure the string is at least 5 characters in length. It will pad spaces at the beginning to get the required length.
  • If we specify hyphen('-') in '%-5s', then it will do the padding at the end.

  • At LINE A, create the Formatter with out passing the StringBuilder, see how we need to change the program to print the required output.
  • At LINE B, change '%5s' to '%10s' and later to '%2s' and see how the spaces are prefixed.
  • Remove the hyphen(-) in LINE C and see how the output changes.
  • Check what will happen if we do not close the Formatter at LINE D. Also replace close with flush and see if it still works.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.