SoFunction
Updated on 2025-05-08

In an article, everyone can thoroughly learn Java formatting output

Preface

Java provides a variety of formatted output methods, mainly through()()andFormatterClasses to implement. Common formatting operations include numbers, dates, strings, etc.

1. Format output method

1. Use the() method

()The method returns a formatted string without directly printing the output. You can store it in a variable or use it for other processing.

grammar:

(format, arguments);
  • formatIt is a format string containing format specifiers.
  • argumentsis the parameters to be formatted.

Example:

int age = 25;
String formattedString = ("My age is %d", age);
(formattedString);  // Output: My age is 25

2. Use the() method

()Methods print the formatted output directly to the console, similar toprintfFunctions in C language.

grammar:

(format, arguments);

Example:

int age = 25;
("My age is %d\n", age);  // Output: My age is 25

3. Use the Formatter class

FormatterThe class provides more formatting functions, allowing you to create formatted output streams and write them toStringBuilderPrintWriteretc.

Example:

import ; // Import class, used to format strings
public class FormatterExample { // Define a class named FormatterExample    public static void main(String[] args) { // Main method, entry point of the program        Formatter formatter = new Formatter(); // Create a Formatter object to format strings        ("My age is %d", 25); // Use the format method to format the string        // "My age is %d" is a format template, %d is a placeholder, representing an integer        // 25 is the actual value passed to the placeholder %d        (formatter); // Output the formatted string to the console        (); // Close the Formatter object and release the resource    }
}

Code analysis:

  • FormatterClass: Used to format strings. It's similar to()Method, but provides a more flexible formatting method.
  • formatMethod: Accept a formatted template and a set of parameters. The template%dis a placeholder that represents an integer.
  • (formatter)FormatterObject is callingtoString()The method will return the internal formatted string.
  • ():closureFormatterObject, release resources related to it. This is a good programming habit, especially when dealing with I/O resources.

After running this code, the console will output:

My age is 25

2. Common format specifiers:

1. Integer type format specifier

  • %d: Decimal integer.

    • Used to format integers (for example:123)。
    • Example:("%d\n", 123);Output:123
  • %o: Octal integer.

    • An octal representation for outputting integers.
    • Example:("%o\n", 8);Output:10
  • %x: Hexadecimal integer (lowercase letters).

    • Hexadecimal representation (lowercase) used to output integers.
    • Example:("%x\n", 255);Output:ff
  • %X: Hexadecimal integer (capsular letters).

    • Hexadecimal representation (capsular) used to output integers.
    • Example:("%X\n", 255);Output:FF
  • %c: Single character.

    • Used to format a single character.
    • Example:("%c\n", 'A');Output:A

2. Floating point type format specifier

  • %f: Floating point number.

    • The default output is a floating point number, with six digits after the decimal point.
    • Example:("%f\n", 123.456);Output:123.456000
  • %.nf: Floating point number (preserves n decimal places).

    • Used to format floating point numbers and specify the number of decimal places reserved.
    • Example:("%.2f\n", 123.456);Output:123.46
  • %e: Scientific notation method (lowercase letters).

    • Used to format floating point numbers as scientific notation representations (lowercase letters).
    • Example:("%e\n", 1234567.89);Output:1.234568e+06
  • %E: Scientific notation method (capital letters).

    • Used to format floating point numbers as scientific notation representations (capsular letters).
    • Example:("%E\n", 1234567.89);Output:1.234568E+06
  • %g: Automatically select floating or scientific notation (lowercase letters).

    • Automatically select floating or scientific notation based on the size of the number.
    • Example:("%g\n", 1234567.89);Output:1234567.89
  • %G: Automatically select floating or scientific notation (capsular letters).

    • Automatically select floating or scientific notation (capsular letters) based on the size of the number.
    • Example:("%G\n", 1234567.89);Output:1234567.89

3. String format specifier

  • %s: String.
    • Used to format strings.
    • Example:("%s\n", "Hello, World!");Output:Hello, World!

4. Date and time format specifiers

The format specifier for date and time is%tThe beginning, followed by a specific type of date/time.

  • %tY: Year (four digits).

    • Example:("%tY\n", new Date());Output:2025
  • %tm: Month (numbers indicate, 01 to 12).

    • Example:("%tm\n", new Date());Output:01
  • %td: Date (numbers indicate, 01 to 31).

    • Example:("%td\n", new Date());Output:21
  • %tB: Month (full English name).

    • Example:("%tB\n", new Date());Output:January
  • %tD: Date (MM/DD/YY format).

    • Example:("%tD\n", new Date());Output:01/21/25
  • %tH: Hours (24-hour time, 00 to 23).

    • Example:("%tH\n", new Date());Output:14
  • %tM: Minutes (00 to 59).

    • Example:("%tM\n", new Date());Output:30
  • %tS: seconds (00 to 59).

    • Example:("%tS\n", new Date());Output:45
  • %tT: Time (HH:MM:SS format).

    • Example:("%tT\n", new Date());Output:14:30:45
  • %tF: Full date (YYYY-MM-DD format).

    • Example:("%tF\n", new Date());Output:2025-01-21

5. Percent sign format specifier

  • %%: Output a percent sign.
    • Example:("100%%\n");Output:100%

6. Other formatting control characters

  • %n: Line breaks (platform independent line breaks).

    • Example:("Hello%nWorld%n");Output:Hello(Line-wind)World(Line-wind)
  • %b: Boolean type.

    • Example:("%b\n", true);Output:true

3. Common formatting options:

1. Width (Width)

The width option controls the minimum character width of the output data. If the formatted content is less than the specified width, Java fills the remaining space based on other options, such as fillers.

grammar:

%[width]specifier
  • width: Specify the minimum output width.
  • specifier: Format specifier (such as%d%f%swait).

Example:

("|%10d|\n", 123);   // Output: | 123|("|%-10d|\n", 123);  // Output: |123 |
  • |%10d|: The output width is 10. If the number is less than 10 characters in width, the previous one will be filled with spaces.
  • |%-10d|: The output width is 10, left-aligned, and fill it with spaces afterwards.

2. Precision

Precision is used to control the number of decimal places of a floating point number and the maximum length of a string.

2.1. Accuracy of floating point numbers:

For floating point numbers, you can specify the number of digits that are reserved after the decimal point.

grammar:

%.[precision]f
  • precision: Specify the number of digits after the decimal point of the floating point.

Example:

("%.2f\n", 123.456);  // Output: 123.46("%.3f\n", 123.456);  // Output: 123.456
  • %.2f: Keep 2 decimal places.
  • %.3f: Keep 3 decimal places.

2.2. Precision of string:

For strings, you can specify the maximum number of characters to the output string.

Example:

("%.5s\n", "HelloWorld");  // Output: Hello
  • %.5s: Output the first 5 characters of the string.

3. Padding Character

The filler character is used to control the blank position being filled with specified characters when the data is not wide enough. By default, Java will be filled with spaces, but we can specify other characters (such as0) as a filler.

grammar:

%[fill_char][width]specifier
  • fill_char: Fill in characters.
  • width: Minimum output width.
  • specifier: Format specifier.

Example:

("|%010d|\n", 123);  // Output: |0000000123|("|%-10d|\n", 123);  // Output: |123 |
  • |%010d|: The specified width is 10, used before0Fill.
  • |%-10d|: Specify the width to be 10, align left, and fill it with spaces afterwards.

4. Alignment

By default, numbers and strings are right-aligned. But the alignment can be changed by specifying symbols.

  • -: Left aligned.
  • Default is right-aligned.

Example:

("|%-10d|\n", 123);  // Output: |123 | Left Alignment("|%10d|\n", 123);   // Output: | 123 | Right aligned (default)
  • %-10d: left-aligned, the output width is 10.
  • %10d: Right aligned, the output width is 10.

5. Percent sign (%%)

If we need to output an actual percent sign character, we can use%%

Example:

("The success rate is 100%%.\n");  // Output: The success rate is 100%.

6. Date and Time Format

The formatting of dates and time supports options such as width and precision. We can control the width and fill mode of the date/time output.

Example:

("%tY-%tm-%td\n", new Date());  // Output: 2025-01-21 (Date format: YYYY-MM-DD)

7. Combination of width and precision

We can use a combination of width and precision to further control the output format. For example, control the total width of a floating point number and the number of decimal places.

Example:

("|%10.2f|\n", 123.456);  // Output: | 123.46|
  • |%10.2f|: The total width is 10, and 2 digits are retained after the decimal point.

8. Automatically select floating or scientific notation methods (%g and %G)

  • %g: Automatically select to use floating (normal notation) or scientific notation (lowercase letters).
  • %G: Automatically select to use floating (normal notation) or scientific notation (capsular letters).

Example:

("%g\n", 1234567.89);   // Output: 1234567.89("%g\n", 0.000123456);  // Output: 1.23456e-04("%G\n", 1234567.89);   // Output: 1234567.89("%G\n", 0.000123456);  // Output: 1.23456E-04

9. Combining alignment with filler

When used in combination with alignment options, the format of the output can be controlled very carefully, and is often used in table output, etc.

Example:

("|%0-10d|\n", 123);  // Output: |123 | Left aligned and filled with 0//However, 0 and - are mutually exclusive, because - means left-aligned, while 0 means fill in the blank with 0.//When they appear at the same time, the behavior of 0 will be ignored, only - will take effect.
("|%0+10d|\n", 123);  // Output: |+0000123| Right aligned and filled with 0, signed

4. Format date:

Date formatting in Java usually depends onClasses are implemented, but if used()or(), date formatting is passedtThe format specifier of the series is carried out.

1.%t series format specifier

The format specifier for date and time is%tstart and follow a letter to indicate different date and time parts. Common date formatting specifiers are as follows (described in detail in the previous article):

Date section:

  • %tY: Year (four digits, e.g.2025)。
  • %tm: Month (two digits, e.g.0112)。
  • %td: Date (two digits, e.g.0131)。
  • %tB: Complete month name (e.g.JanuaryDecember)。
  • %tD: Date (MM/DD/YY format, for example01/21/25)。

Time part:

  • %tH: Hours (24-hour time, 00 to 23).
  • %tM: Minutes (00 to 59).
  • %tS: seconds (00 to 59).
  • %tI: Hours (12-hour time, 01 to 12).
  • %tp:AM/PM (AM/PM).
  • %tT: Time (HH:MM:SS format, e.g.14:30:45)。

Complete date and time format:

  • %tF: Full date (YYYY-MM-DD format, e.g.2025-01-21)。
  • %tR: Time (HH:MM format, e.g.14:30)。

2. Date formatting example

Example 1: Format the full date (YYYY-MM-DD)

import ; // Import class to represent date and time
public class DateFormatExample { // Define a class named DateFormatExample    public static void main(String[] args) { // Main method, entry point of the program        Date date = new Date(); // Create a Date object representing the current date and time        ("Formatted date: %tF\n", date); // Output: 2025-01-21        // Format dates using printf method        // %tF is a formatted placeholder that indicates the date of output in ISO 8601 format (yyyy-MM-dd)        // date is the actual date object passed to the placeholder        // The output result is: Formatted date: 2025-01-21 (assuming the current date is January 21, 2025)    }
}
  • %tFOutput the complete date, formatYYYY-MM-DD

Example 2: Format time (HH:MM:SS)

import ; // Import class to represent the current date and time
public class DateFormatExample { // Define a class named DateFormatExample    public static void main(String[] args) { // Main method, entry point of the program        Date date = new Date(); // Create a Date object representing the current date and time        ("Formatted time: %tT\n", date);  // Output: 14:30:45        // Format the time using the printf method        // %tT is a formatted placeholder that indicates the output time in 24-hour format (HH:mm:ss)        // date is the actual date object passed to the placeholder        // The output result is: Formatted time: 14:30:45 (assuming the current time is 14:30:45)    }
}
  • %tTOutput time, formatHH:MM:SS

Example 3: Formatted as Month Day, Year

import ; // Import class to represent date and time
public class DateFormatExample { // Define a class named DateFormatExample    public static void main(String[] args) { // Main method, entry point of the program        Date date = new Date(); // Create a Date object representing the current date and time        ("Formatted date with month name: %tB %td, %tY\n", date, date, date); // Output: January 21, 2025        // Use the printf method to format the date and include the month name in the output        // %tB: Formatted as the full name of the month (such as January, February, etc.)        // %td: The number of days that are formatted as date (e.g. 01 to 31)        // %tY: Formatted as a four-bit year (for example, 2025)        // date is the actual date object passed to the placeholder. The date is passed three times here, corresponding to %tB, %td and %tY respectively        // The output result is: Formatted date with month name: January 21, 2025 (assuming the current date is January 21, 2025)    }
}
  • %tBOutput the full month name,%tdOutput date,%tYOutput year.

Example 4: Formatted to 12-hour (AM/PM)

import ; // Import class to represent date and time
public class DateFormatExample { // Define a class named DateFormatExample    public static void main(String[] args) { // Main method, entry point of the program        Date date = new Date(); // Create a Date object representing the current date and time        ("Formatted time in 12-hour format: %tI:%tM %tp\n", date, date, date); // Output: 02:30 PM        // Use the printf method to format the time and output in a 12-hour format        // %tI: The hourly part formatted to a 12-hour time frame (01 to 12)        // %tM: Formatted as minute portion (00 to 59)        // %tp: Formatted as AM or PM        // date is the actual date object passed to the placeholder. The date is passed three times here, corresponding to %tI, %tM and %tp respectively        // The output result is: Formatted time in 12-hour format: 02:30 PM (assuming the current time is 14:30)    }
}
  • %tIOutput the number of hours in a 12-hour system,%tMOutput minutes,%tpOutput AM/PM.

3. Format the combination of date and time

We can also combine date and time format specifiers to display the full date and time.

Example: Full format of date and time (YYYY-MM-DD HH:MM:SS)

import ;

public class DateFormatExample {
    public static void main(String[] args) {
        Date date = new Date();
        ("Formatted date and time: %tF %tT\n", date, date);  // Output: 2025-01-21 14:30:45    }
}
  • %tFUsed to format the date part (YYYY-MM-DD).
  • %tTUsed to format the time part (HH:MM:SS).

4. Control output width and fill

Of course, like other formatting types, we can also control the width of the date and time output and how to fill in the blanks. By specifying the width, the output can be ensured to meet the requirements.

Example: Control date width

import ; // Import class to represent date and time
public class DateFormatExample { // Define a class named DateFormatExample    public static void main(String[] args) { // Main method, entry point of the program        Date date = new Date(); // Create a Date object representing the current date and time        ("|%20tF|\n", date);  // Use the printf method to format the date and output it        // %tF: The format date is ISO 8601 format, i.e. yyyy-MM-dd (for example, 2025-01-21)        // 20: Specify the field width to 20 characters        // By default, the string is right-aligned, so the left side is filled with spaces to reach the specified width        // The output result is: | 2025-01-21| (assuming that the current date is 2025-01-21)    }
}
  • %20tFIndicates that the width is 20, and the insufficient part will be filled with spaces.

Example: Control time width and fill

import ; // Import class to represent date and time
public class DateFormatExample { // Define a class named DateFormatExample    public static void main(String[] args) { // Main method, entry point of the program        Date date = new Date(); // Create a Date object representing the current date and time        ("|%10tT|\n", date);  // Use the printf method to format the time and output it        // %tT: The formatting time is 24 hours format, i.e. HH:mm:ss (for example, 14:30:45)        // 10: Specify the field width to 10 characters        // By default, the string is right-aligned, so if the formatted time string length is less than 10 characters,        // The left side will be filled with spaces to reach the specified width        // The output result is: |14:30:45 | (assuming the current time is 14:30:45)    }
}
  • %10tTThe width of the specified time is 10, and the left side is filled with spaces.
  • If left alignment is required, you can add it in the formatted placeholder-Symbols, for example:%-10tT. This way, the spaces will fill on the right.

5. Date formatting is used in combination with SimpleDateFormat class

()and()Applicable to simple date formatting, but if you need more complex formatting (such as custom formatting), you can useSimpleDateFormatkind.

Example: Custom date formatting (using SimpleDateFormat)

import ; // Import the SimpleDateFormat class for custom date and time formattingimport ; // Import the Date class to represent date and time
public class SimpleDateFormatExample { // Define a class named SimpleDateFormatExample    public static void main(String[] args) { // Main method, entry point of the program        Date date = new Date(); // Create a Date object representing the current date and time        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
        // Create a SimpleDateFormat object for customizing date and time formatting        // "yyyy/MM/dd HH:mm:ss" is a formatting template:        // yyyy: four-digit year        // MM: Two months        // dd: two digit date        // HH: Two-digit 24-hour hours        // mm: two digits        //ss: two digit seconds        String formattedDate = (date); 
        // Use the format method to format the Date object to the specified string format        ("Formatted date and time: " + formattedDate); 
        // Output the formatted date and time        // For example: Formatted date and time: 2025/01/21 14:30:45 (assuming the current time is January 21, 2025 at 14:30:45)    }
}
  • SimpleDateFormatAllows you to create a custom date format, such as"yyyy/MM/dd HH:mm:ss"
  • SimpleDateFormatIt is thread-insecure, so special attention is required when used in multi-threaded environments.
  • If you need a thread-safe date formatting tool, you can use(Java 8 and above).

Summarize

  • ()Returns the formatted string.
  • ()Directly output the formatted string to the console.
  • FormatterProvides more control and can be used to customize output streams.

This is the end of this article about Java formatting output. For more related Java formatting output content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!