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
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'.
THINGS TO TRY
- Interchange the parameters
"Merit Campus" and
90 and see what will be the output.
- Pass additional parameters like
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 '
The below table shows various format specifiers and there importance.
Try formatting various values like
using the appropriate format specifiers.