java.util.Formatter class is used for formatting the values passed to the format() method. This class become part of Java since the Java 5 release. This feature is taken from the C language to format the string, numbers, date, etc. in the simplified manner. There is set of variables and expression defined for formatting the values.
also read:
The formatted values can be either printed in the console and can be written to the file. This feature can be configured in the java.util.Formatter constructor. This API has huge number of constructors and options for the formatting. We have written a very simple example to demonstrate the use of this class.
Lets look at the example:
JavaFormatterExample.java
package javabeat.net.java.core; import java.util.Calendar; import java.util.Formatter; /** * java.util.Formatter Example * * @author Krishna * */ public class JavaFormatterExample { public static void main(String args[]) { Formatter format1 = new Formatter(); //Formatting numbers format1.format("Formatting %s : int ( %d ) float ( %f )", "numbers example ", 10, 98.6); System.out.println(format1); //Formatting date and time Formatter format2 = new Formatter(); Calendar cal = Calendar.getInstance(); format2.format("%tr", cal); System.out.println(format2); format2 = new Formatter(); format2.format("%tc", cal); System.out.println(format2); format2 = new Formatter(); format2.format("%tl:%tM", cal, cal); System.out.println(format2); format2 = new Formatter(); format2.format("%tB %tb %tm", cal, cal, cal); System.out.println(format2); } }
Output…
Formatting numbers example : int ( 10 ) float ( 98.600000 ) 02:42:16 PM Mon Jun 23 14:42:16 IST 2014 2:42 June Jun 06