Topics Index

More Utility Classes > Formatter >
Siva Nookala - 20 Feb 2017
Formatting the output we display to the end users is important, since it has to be easy to read and should confirm to the local needs of the user. Otherwise the data like dates and amounts might be misinterpreted by the users. We will understand how the Formatter works using a simple program.

Basic Formatter Demo
import java.util.*;

class BasicFormatterDemo
    public static void main(String arg[])
        Formatter formatter = new Formatter();
        formatter.format("Learn Java with %s in %d days and score %f", "Merit Campus", 90, 98.6);

Learn Java with Merit Campus in 90 days and score 98.600000


Here we created the most basic form of Formatter which takes no parameter. So it uses StringBuilder as the underlying resource and the Locale will the default locale. If you carefully observe the first parameter in the format method, we are defining how to format the content by using the % symbol. Then we are passing multiple parameters. The first % symbol will be replaced with the first parameter and second % symbol with the second parameter and the third % with the third parameter. So where '%s' is present, it will replace the first parameter, that is nothing but "Merit Campus". Where '%d' is present, we replace it with 90 and where '%f', it will replace with 98.6000 since that is the third parameter.

Also note that apart from the order, the parameter type is also important. For Strings we use '%s', for integers '%d' and for floating types we use '%f'.

  • Interchange the parameters "Merit Campus" and 90 and see what will be the output.
  • Pass additional parameters like 'C' and true and see that those parameters are not included in the output.
  • Try removing the parameter 98.6 and see that it throws an exception, since it does not know what to place at '%f'.
The below table shows various format specifiers and there importance.
Format SpecifierConversion Applied
%a %AFloating-point hexadecimal
%b %BBoolean
%dDecimal Integer
%h %HHash code of the argument
%e %EScientfic notation
%fDecimal floating-point
%g %GUses %e or %f, whichever is shorter
%oOctal Integer
%nInserts a newline character
%s %SString
%t %TTime and date
%x %XInteger hexadecimal
%%Inserts a % sign
Try formatting various values like 234, 0234, 0x234, true, 'D', 23.45, 23E4, "Learn Java", new Date() using the appropriate format specifiers.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.