SoFunction
Updated on 2025-03-09

About formatting output method

The () method is a formatted output method in Java. It formats different types of data into strings of specified formats and stores the results in strings.

Method parameters

String format(String format, Object... args)
  • format: The string format to be returned
  • args: The value to be replaced in the format

The format can contain several placeholders, and the placeholder consists of a percent sign followed by a format type character.

Common placeholders

Placeholder type describe
s String Usually used for string type and arbitrary objects, the toString() method that outputs any object returns the value
d Integer Usually used for integer types and primitive types such as byte, short, int, long
f Floating point number Usually used for floating point types and primitive types such as float and double
c character Usually used for primitive types such as character types and char
b Boole Usually used for boolean types and boolean types
t Date/Time Commonly used for date and time types
e Scientific Counting Method It is often used to format floating point numbers into scientific notation.

Placeholder usage

- %s: string

String format1 = ("Name: %s, Gender: %s", "Li Haha", "male");
(format1);

Name: Li Haha, Gender: Male

- %d: integer

String format2 = ("Age: %d", 28);
(format2);

Age: 28

- %f: floating point number

String format3 = ("Chinese: %f, mathematics: %f", 95.5, 99.5);
(format3);

Chinese: 95.500000, Mathematics: 99.500000

- %c: Characters

String format4 = ("Chinese: %c, mathematics: %c", 'A', 'B');
(format4);

Chinese: A, Mathematics: B

- %b: Boolean

String format5 = ("True: %b, false: %b, true: %b, true: %b, true: %b", true, false, "", 0, -1);
(format5);

True: true, false: false, true: true, true: true, true: true

Note: Except for false, all other values ​​are output as true.

- %t: date/time

String format6 = ("Today is: %tF", new Date());
(format6);

Today is: 2023-06-15

Note: %t cannot be used directly alone, and must follow other letters to specify the time format.

- %e: Scientific notation method

String format7 = ("%e", 950000000.1);
(format7);

9.500000e+08

Special usage method

- Specify the minimum width

A number can be added between the % symbol and the placeholder, which represents the minimum width of the placeholder.

  • If the number of characters that need to fill this width is insufficient, it will be automatically aligned with the - sign in front of it and the left alignment will be made.
  • If this width is exceeded, all characters are preserved.
String s1 = ("|%20s|", "Hello");
String s2 = ("|%-20s|", "Hello");
String s3 = ("|%20c|", 'A');
String s4 = ("|%20c|", 'A');
String s5 = ("|%20d|", 1);
String s6 = ("|%-20d|", 1);
String s7 = ("|%20f|", 1.0);
String s8 = ("|%-20f|", 1.0);
String s9 = ("|%-20b|", true);
String s10 = ("|%-20b|", true);
String s11 = ("|%-20tF|", new Date());
String s12 = ("|%-20tF|",  new Date());
(s1);
(s2);
(s3);
(s4);
(s5);
(s6);
(s7);
(s8);
(s9);
(s10);
(s11);
(s12);

|               Hello|
|Hello               |
|                   A|
|                   A|
|                   1|
|1                   |
|            1.000000|
|1.000000            |
|true                |
|true                |
|2023-06-15          |
|2023-06-15          |

- Specify fill characters

You can add padding characters between the % symbol and placeholder to specify the characters to use. The default fill character is a space (the example of specifying the minimum width above is a padded space), and the supported fill characters:

  • Spaces: Use spaces to fill when the width is not enough
  • 0: When the width is not enough, you can use 0 to fill it.
  • +: Add symbols for positive or negative numbers
  • -: left aligned (default is right aligned)
  • ,: Number specified in the form of a group separator (one comma for every 3 digits)
  • #: For digits with optional prefixes such as binary, octal, hexadecimal, etc., the prefix will be displayed.
  • .: Precision or string truncation point
  • $: Reference parameters in order
String s1 = ("%10s", "hello");
String s2 = ("%010d", 42);
String s3 = ("%+d", 42);
String s4 = ("%-10s", "hello");
String s5 = ("%,d", 1234567890);
String s6 = ("%#x", 42);
String s7 = ("%.2f", 3.1415926);
String s8 = ("%1$s %2$s", "hello", "world");

(s1);
(s2);
(s3);
(s4);
(s5);
(s6);
(s7);
(s8);

     hello
0000000042
+42
hello     
1,234,567,890
0x2a
3.14
hello world

- Determine the accuracy

For floating point number types and other numeric types, precision can be used to specify decimal or significant numeric digits. The accuracy is represented by a dot (.) and a number.

double f = 1234.56789;

String s1 = ("%.2f", f);
String s2 = ("%.4f", f);
String s3 = ("%+.2f", f);

(s1);
(s2);
(s3);

1234.57
1234.5679
+1234.57

In this example, .2f means keeping two decimal places, .4f means keeping four decimal places, and %+.2f means keeping two decimal places, preceding the positive number with a plus sign.

- Date formatting

The placeholder %t can be followed by letters to represent the time format.

  • %tB: The month of the date, full name, for example: June
  • %tb: the month of the date, abbreviation, for example: Jun
  • %tm: month of date, double digits, for example: 06
  • %tY: 4-digit year, for example: 2023
  • %ty: 2-digit year, for example: 23
  • %tk: 24-hour hours without leading zeros, for example: 20
  • %tH: 24-hour hour time, double digit number, for example: 20
  • %tl: 12-hour hours without leading zeros, for example: 8
  • %tI: 12-hour hours, double digits, for example: 08
  • %tM: minutes, double digits, for example: 30
  • %tS: seconds, double digits, for example: 45
  • %tL: milliseconds, triple digits, for example: 886
  • %tN: nanoseconds, 9 digits, for example: 886456123
  • %tp: morning/afternoon (with different upper and lower cases), for example: morning
  • %tz: Time zone offset, for example: +0800
  • %tZ: time zone abbreviation, for example: CST
  • %tj: What day of the year, for example: 166
  • %tD:.Date format (MM/DD/YY), for example: 06/15/23
  • %tF: ISO date format, for example: 2023-06-15
  • %tc: full date and time, for example: Wed Jun 15 07:32:24 CST 2023
  • %tr: 12-hour format time (AM/PM), for example: 02:45:30 PM
  • %tR: 24 hours format time (format is HH:mm)
  • %tT: 24 hours format time, for example: 14:45:30
  • %ts: The number of seconds starting from 00:00:00 GMT on January 1, 1970, for example: 168412870
  • %tQ: Number of milliseconds starting from 00:00:00 GMT on January 1, 1970, for example: 168412870886
Calendar c = ();
Date date = ();

String s1 = ("%tB", date);
String s2 = ("%tb", date);
String s3 = ("%tm", date);
String s4 = ("%tY", date);
String s5 = ("%ty", date);
String s6 = ("%tk", date);
String s7 = ("%tH", date);
String s8 = ("%tl", date);
String s9 = ("%tI", date);
String s10 = ("%tM", date);
String s11 = ("%tS", date);
String s12 = ("%tL", date);
String s13 = ("%tN", date);
String s14 = ("%tp", date);
String s15 = ("%tz", date);
String s16 = ("%tZ", date);
String s17 = ("%tj", date);
String s18 = ("%tD", date);
String s20 = ("%tF", date);
String s21 = ("%tc", date);
String s22 = ("%tr", date);
String s23 = ("%tR", date);
String s24 = ("%tT", date);
String s25 = ("%ts", date);
String s26 = ("%tQ", date);

("Current time:"+(date, "yyyy-MM-dd HH:mm:ss"));
("%tB:" + s1);
("%tb:" + s2);
("%tm:" + s3);
("%tY:" + s4);
("%ty:" + s5);
("%tk:" + s6);
("%tH:" + s7);
("%tl:" + s8);
("%tI:" + s9);
("%tM:" + s10);
("%tS:" + s11);
("%tL:" + s12);
("%tN:" + s13);
("%tp:" + s14);
("%tz:" + s15);
("%tZ:" + s16);
("%tj:" + s17);
("%tD:" + s18);
("%tF:" + s20);
("%tc:" + s21);
("%tr:" + s22);
("%tR:" + s23);
("%tT:" + s24);
("%ts:" + s25);
("%tQ:" + s26);

Current time: 2023-06-15 16:04:26
%tB: June
%tb: June
%tm:06
%tY:2023
%ty:23
%tk:16
%tH:16
%tl:4
%tI:04
%tM:04
%tS:26
%tL:536
%tN:536000000
%tp: afternoon
%tz:+0800
%tZ:CST
%tj:166
%tD:06/15/23
%tF:2023-06-15
%tc: Thursday June 15 16:04:26 CST 2023
%tr: 04:04:26 pm
%tR:16:04
%tT:16:04:26
%ts:1686816266
%tQ:1686816266536

- Add a percent sign %

To print the percent sign % character in a formatted string, you can use %% to represent it.

int n = 42;

String s = ("%d%%", n);

(s);

42%

- Reference parameters in order

Specifies the reference order of the parameters, add [number]$ between % and letters to specify which parameter to refer to.

String s = ("The second parameter is: %2$s, the third parameter is: %3$s, the first parameter is: %1$s", "hello", "world", "java");
(s);

The second parameter is: world, the third parameter is: java, the first parameter is: hello

Efficiency issues

() Compared with other string splicing methods, it has high flexibility in formatting output, but it is indeed not as efficient as other splicing methods, such as splicing strings with StringBuilder or StringBuffer.

  • When using(), Java creates a new string object, which is the result of the formatted output and returns it to the caller. However, when creating the string result, Java requires a lot of string splicing and processing operations, so this process will be time-consuming.
  • In contrast, when using StringBuilder or StringBuffer to splice strings, we can splice all strings at once, avoiding creating new string objects multiple times. Therefore, this method is usually more efficient to build strings than using().

In actual programming, we need to choose the most suitable string splicing method based on specific business scenarios and needs, which not only considers efficiency issues, but also takes into account the readability and maintainability of the code.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.