java.util.Formatter Example

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:


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);

		//Formatting date and time
		Formatter format2 = new Formatter();
		Calendar cal = Calendar.getInstance();

		format2.format("%tr", cal);

		format2 = new Formatter();
		format2.format("%tc", cal);

		format2 = new Formatter();
		format2.format("%tl:%tM", cal, cal);

		format2 = new Formatter();
		format2.format("%tB %tb %tm", cal, cal, cal);


Formatting numbers example  : int ( 10 )  float ( 98.600000 )
02:42:16 PM
Mon Jun 23 14:42:16 IST 2014
June Jun 06

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!