Java String.format() Example

By Arvind Rai, November 29, 2022
On this page we will learn using String.format() method in our Java application. The String.format() formats the given string using the format string syntax.
Find the Java doc of String.format() method.
1.
static String format(String format,  Object... args) 
Returns a formatted string.
2.
static String format(Locale locale, String format, Object... args) 
Returns a formatted string.
3. Find the Java doc of String.formatted() method.
String formatted(Object... args) 
Formats this string and returns the formatted string.

Parameters :
The locale is the Locale to apply during formatting.
The format is a format string.
The args are the arguments referenced by the format specifiers in the format string. The number of arguments is variable. If there are more arguments than format specifiers, the extra arguments are ignored.

Throws :
IllegalFormatException : If a format string contains an illegal syntax.

1. Format String Syntax

Find the format string syntax.
1. Format specifiers for general, character and numeric types.
%[argument_index$][flags][width][.precision]conversion 
2. Format specifiers for date and time.
%[argument_index$][flags][width]conversion 
3. The format specifiers which do not correspond to arguments.
%[flags][width]conversion 

1.1 argument_index

The argument_index is optional. It represents a decimal integer that indicates the position of the argument in the argument list. For example, first argument is referenced by "1$", second by "2$", third by "3$" and so on.

1.2 flags

The flags is optional. It is a set of characters that modify the output format.
FlagDescription
'-'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

1.3 width

The width is optional. It is a non-negative decimal integer that indicates the minimum number of characters to be written to the output.

1.4 precision

The precision is optional. It is non-negative decimal integer that is used to restrict the number of characters to be written to the output.

1.5 conversion

The conversion is a required character that indicates how the argument should be formatted.
The conversions are divided into the categories such as General, Character, Integral, Floating Point, Date/Time, Percent and Line Separator.

1. Categories: General, Character, Integral, Floating Point, Percent and Line Separator
ConversionDescription
'b', 'B'If the argument 'arg' is null, then the result is "false".
'h', 'H'The result is obtained by invoking Integer.toHexString
's', 'S'If arg implements Formattable, then arg.formatTo is invoked.
'c', 'C'The result is a Unicode character.
'd'The result is formatted as a decimal integer.
'o'The result is formatted as an octal integer.
'x', 'X'The result is formatted as a hexadecimal integer.
'e', 'E'The result is formatted as a decimal number in computerized scientific notation.
'f'The result is formatted as a decimal number.
'g', 'G'The result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.
'a', 'A'The result is formatted as a hexadecimal floating-point number with a significand and an exponent.
't', 'T'Prefix for date and time conversion characters.
'%'The result is a literal '%'.
'n'The result is the platform-specific line separator.

2. Category: Date/Time
ConversionDescription
'H'Hour of the day with two digit (00 - 23)
'I'Hour for the 12-hour clock (01 - 12)
'k'Hour of the day (0 - 23)
'l'Hour for the 12-hour clock (1 - 12)
'M'Minute within the hour (00 - 59)
'S'Seconds within the minute (00 - 60)
'L'Millisecond within the second (000 - 999)
'N'Nanosecond within the second (000000000 - 999999999)
'p'Locale-specific morning or afternoon marker in lower case
's'Seconds since the beginning of the epoch
'Q'Milliseconds since the beginning of the epoch
'B'Locale-specific full month name ("January", "February")
'b'Locale-specific abbreviated month name ("Jan", "Feb")
'A'Locale-specific full name of the day of the week ("Sunday", "Monday")
'a'Locale-specific short name of the day of the week ("Sun", "Mon")
'y'Last two digits of the year (00 - 99)
'm'Month (01 - 13)
'd'Day of month (01 - 31)
'e'Day of month (1 - 31)
'R'Time formatted for the 24-hour clock as "%tH:%tM"
'T'Time formatted for the 24-hour clock as "%tH:%tM:%tS"
'r'Time formatted for the 12-hour clock as "%tI:%tM:%tS %Tp"
'D'Date formatted as "%tm/%td/%ty"
'F'ISO 8601 complete date formatted as "%tY-%tm-%td"
'c'Date and time formatted as "%ta %tb %td %tT %tZ %tY"

2. String.format() method Example

1. Using conversion only.
String name = "Krishn";
int age = 35;
String s = String.format("Name %s and age %d", name, age);
System.out.println(s); // Name Krishn and age 35 
Here s and d are the conversions for string and integer respectively.

2. Using argument_index and conversion.
String s = String.format("Name %2$s and age %1$d", age, name);
System.out.println(s); // Name Krishn and age 35 
Here 1$ and 2$ are the argument index. The value of age will appear at %1$d place and value of name will appear at %2$s place.

3. Using argument_index, flags, width and conversion.
String s = String.format("Name |%2$10s| and age |%1$-10d|", age, name);
System.out.println(s); 
Output
Name |    Krishn| and age |35        | 
In %1$-10d string, 1$ is argument index, - is flag, 10 is width and d is conversion.
In %2$10s string, 2$ is argument index, 10 is width (default flag is + ) and s is conversion .

4. Using precision.
String s = String.format("Num: |%1$-20.6f|", 45.345);
System.out.println(s); 
Output
Num: |45.345000           | 
In %1$-20.6f string, .6 is precision and f is the conversion for floating point.

5. Formatting date.
Calendar c = new Builder().setDate(1985, 10, 14).build();
String s = String.format("Ram's Birthday: %1$tm %1$te,%1$tY", c);
System.out.println(s); 
Output
Ram's Birthday: 11 14,1985 
t is the prefix for date and time conversions characters.
m is the conversion for month.
e is the conversion for day of month.
Y is the conversion for year.

6. Formatting time.
LocalTime time = LocalTime.of(10, 25, 35);  
String s = String.format("Time: %1$tR", time);
System.out.println(s); 
Output
Time: 10:25 
t is the prefix for date and time conversions characters.
R is the conversion for time.

3. String.format() method with Locale

Here we will use Locale with String.format() method.
Find the code to use flag , for number.
String uk = String.format(Locale.UK, "Num: %1$,d", 456347854);
System.out.println(uk); // Num: 456,347,854 

4. String.formatted() method Example

Find the example to use String.formatted().
String s1 = "Name %1$s and age %2$d".formatted("Ram", 25);
System.out.println(s1); // Name Ram and age 25

Calendar c = new Builder().setDate(1985, 10, 14).build();
String s2 = "Birthday: %1$tm %1$te,%1$tY".formatted(c);
System.out.println(s2); // Birthday: 11 14,1985 

5. References

Class String
Class Formatter
POSTED BY
ARVIND RAI
ARVIND RAI











©2023 concretepage.com | Privacy Policy | Contact Us