Menu
Topics Index
...
`

Basic Formatter Demo - Java Example 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);
        
        System.out.println(formatter);
        formatter.close();    
    }
}
OUTPUT

Learn Java with Merit Campus in 90 days and score 98.600000

DESCRIPTION

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 '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'.

© meritcampus 2019

All Rights Reserved.

Open In App