Home  >  Core Java

Java Formatter format()

By Arvind Rai, September 21, 2021
On this page we will walk through Java Formatter.format method. The java.util.Formatter class works as an interpreter for printf-style format strings. The Formatter can perform layout justification, alignment, common formats for numeric, string and date/time data. The Formatter produces locale specific output.
To format data, Formatter has format() method as following.
a.
Formatter format(String format, Object... args) 
1. Writes a formatted string to this object’s destination using the specified format and arguments. The default locale is same which one is used during the construction of formatter.
2. Returns this formatter.
3. There is IllegalFormatException if format string contains illegal syntax, incompatible format specifiers or insufficient arguments.
4. If there are more than required arguments, the extras will be ignored.

b.
Formatter format(Locale l, String format, Object... args) 
Writes a formatted string to this object’s destination using the specified locale, format, and arguments.
In this method, we can specify locale to format string and rest are same as in the first method.

Now here we will discuss initializing Formatter, format syntax and examples with format() method.



1. Initialization of Formatter

Find some of the constructors of Formatter class.
1.
Formatter() 
Constructs a new Formatter with default locale and default charset for this instance of JVM. The destination of the formatted output is StringBuilder.
2.
 
Formatter(Locale l) 
Constructs a new Formatter with specified locale and default charset for this instance of JVM. The destination of the formatted output is StringBuilder.
3.
Formatter(File file) 
Constructs a new formatter with the specified file. It uses default locale and default charset for this instance of JVM. The destination of this formatter is specified file.
4.
Formatter(File file, Charset charset, Locale l) 
Constructs a new formatter with the specified file, charset, and locale. The destination of this formatter is the specified file.

2. Format Syntax and Examples

Find the format syntax used by Formatter class.
a. For general, character, and numeric types.
%[argument_index$][flags][width][.precision]conversion 
argument_index: Position of argument in the argument list. For example, first argument is referenced by "1$", second argument is referenced by "2$" etc. It is optional.
flags: Set of characters that modify the output format. It is optional.
width: Positive decimal integer indicating the minimum number of characters to be written to the output. It is optional.
precision: Positive decimal integer used to restrict the number of characters. It is optional.
conversion: A character indicating how the argument should be formatted. It is required.

b.: For dates and times.
%[argument_index$][flags][width]conversion 
c. Format specifiers which do not corresponds to arguments.
%[flags][width]conversion 
Now find the examples.


2.1 Conversions

Conversions are divided into categories that are general, character, numeric, date/time, percent and line separator.
Find some conversions.
%s For string data.
%d For integer numbers.
%f For floating numbers.
%c For Unicode character.
%t Prefix for date and time.
The date/time conversion suffix are m for month, e for day of month, y for year, H for hour of the day in 24-hour clock, M for minute and S for second.
Date conversions can be used as %tm, %te, %ty, %tH, %tY, %tS .

Example:
1.
Formatter formatter = new Formatter(Locale.US);
String name = "Krishn";
int age = 30;
formatter.format("User name is %s and age is %d", name, age);
System.out.println(formatter); 
Output
User name is Krishn and age is 30 
2.
Formatter formatter = new Formatter(Locale.US);
Calendar c = new GregorianCalendar();
formatter.format("Birth date: %tm %te,%tY", c, c, c);
System.out.println(formatter); 
Output
Birth date: 09 21,2021 

2.2 Argument Index

The argument index is a decimal integer that denotes the position of the argument in the argument list. The argument index referenced by 1$ is for first argument and 2$ is for second argument and so on.
Example:
1.
Formatter formatter = new Formatter(Locale.US);
Formatter f = formatter.format("Numbers: %3$d %1$d %2$d", 10, 20, 30);
System.out.println(f); 
Output
Numbers: 30 10 20 
2.
Formatter formatter = new Formatter(Locale.US);
Calendar c = new GregorianCalendar();
Formatter f = formatter.format("Birth date: %1$tm %1$te,%1$tY %1$tH:%1$tM:%1$tS", c);
System.out.println(f); 
Output
Birth date: 09 21,2021 09:32:26 

2.3 Flags

'-' The result will be left-justified.
'#' The result should use a conversion-dependent alternate form.
'+' The result will always include a sign.
' ' The result will include a leading space for positive values.
'0' The result will be zero-padded
',' The result will include locale-specific grouping separators.
'(' The result will enclose negative numbers in parentheses.

Example:
1.
Formatter formatter = new Formatter();
formatter.format(Locale.GERMAN, "e = %+f", Math.E);
System.out.println(formatter); 
Output
e = +2,718282 
2.
Formatter formatter = new Formatter();
formatter.format(Locale.ENGLISH, "N = %(,d", -123456);
System.out.println(formatter); 
Output
N = (123,456) 

2.4 Width

The width is the minimum number of characters to be written to the output.

Example:
Formatter formatter = new Formatter();
String str = "AB";
formatter.format(Locale.GERMAN, "|%5s|", str);
System.out.println(formatter); 
Output
|   AB| 
We can see that the specified width is 5. It means minimum number of characters to the output is 5. As there are only two characters in ‘str’, so rest are filled with blank spaces.

2.5 Precision

For general conversions like %s, the precision is the maximum number of characters to be written to the output.
For floating-point conversions like %f, the precision is the number of digit after radix point.
For character, integral and date/time conversions, the precision is not applicable.

Example:
1.
Formatter formatter = new Formatter();
String str = "ABCDE";
formatter.format(Locale.GERMAN, "Data: %.3s", str);
System.out.println(formatter); 
Output
Data: ABC 
For %s, precision is the maximum number of characters to be written to the output. In above example, the precision is 3, so output is only 3 characters.
2.
Formatter formatter = new Formatter();
formatter.format(Locale.FRANCE, "%2$s = %1$+5.2f", Math.E, "Formatted E");
System.out.println(formatter); 
Output
Formatted E = +2,72 
In "%1$+5.2f", argument index is 1$, flag is +, width is 5, precision is .2 and conversion is f .

3. Reference

Class Formatter
POSTED BY
ARVIND RAI
ARVIND RAI











©2021 concretepage.com | Privacy Policy | Contact Us