杰瑞科技汇

Java String.format()如何使用?

Of course! String.format() is a powerful and versatile method in Java for creating formatted strings. It works like printf, but instead of printing to the console, it returns the formatted string as a String object. This makes it perfect for building dynamic strings for display, logging, or database operations.

Java String.format()如何使用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering everything from the basics to advanced features.

The Basic Syntax

The method has two primary overloaded forms:

// Format a string with a locale (e.g., for number/decimal formatting)
String formattedString = String.format(Locale locale, formatString, args...);
// Format a string with the default system locale
String formattedString = String.format(formatString, args...);
  • formatString: A string containing static text and special format specifiers.
  • args...: A variable number of arguments (objects, values) that will be inserted into the format string in place of the specifiers.

Format Specifiers: The Core Concept

A format specifier is a placeholder for a value. It always starts with a and ends with a conversion character.

The general structure of a format specifier is:

Java String.format()如何使用?-图2
(图片来源网络,侵删)
%[flags][width][.precision]conversion

Let's break down each part with examples.

Conversion Character

This is the most important part. It specifies the type of data to be formatted.

Conversion Data Type Example Output
s String Hello
d decimal integer (int, long, etc.) 123
f floating-point (float, double) 456
c character (char) A
b boolean true
n platform-independent newline \n on Unix, \r\n on Windows
x integer in hexadecimal 7b
t Date/Time (Requires prefix, see below)

Width

Specifies the minimum number of characters to be written to the output. If the value is shorter, it will be padded with spaces (by default).

int number = 42;
System.out.println(String.format("Number: %5d", number)); // Width 5
// Output: Number:    42 (3 spaces padding)
String name = "Alice";
System.out.println(String.format("Name: %10s", name)); // Width 10
// Output: Name:      Alice (4 spaces padding)

Precision

For floating-point numbers (f), it specifies the number of digits after the decimal point. For strings (s), it specifies the maximum number of characters to be printed.

Java String.format()如何使用?-图3
(图片来源网络,侵删)
double pi = 3.14159;
System.out.println(String.format("Pi: %.2f", pi)); // Precision 2
// Output: Pi: 3.14
String longText = "This is a very long sentence.";
System.out.println(String.format("Text: %.15s", longText)); // Precision 15
// Output: Text: This is a very

Flags

Flags are special characters that modify the output format.

Flag Meaning Example
Left-justify the output (default is right-justify). String.format("%-10s", "Bob") -> Bob
Include a sign ( or ) for numeric values. String.format("%+d", 10) -> +10
0 Pad with zeros instead of spaces. String.format("%05d", 9) -> 00009
Use locale-specific grouping separators (e.g., commas for thousands). String.format("%,d", 1234567) -> 1,234,567
Enclose negative numbers in parentheses. String.format("%,(d)", -100) -> (100)

Date and Time Formatting (t and T)

To format dates and times, you use the t or T conversion, followed by a prefix that defines the specific part of the date/time to format.

import java.util.Calendar;
import java.util.Date;
// Get the current date and time
Calendar now = Calendar.getInstance();
// --- Common Date/Time Specifiers ---
// Y = year, m = month, d = day, H = hour, M = minute, S = second
String formattedDate = String.format("Today is %tY-%tm-%td", now, now, now);
System.out.println(formattedDate);
// Example Output: Today is 2025-10-27
String formattedTime = String.format("The time is %tH:%tM:%tS", now, now, now);
System.out.println(formattedTime);
// Example Output: The time is 14:30:05
// --- Shorthand for repeating arguments ---
// You can use the `<` flag to reuse the same argument from the previous format specifier.
String shortHand = String.format("Date: %tY-%<tm-%<td", now);
System.out.println(shortHand);
// Example Output: Date: 2025-10-27
// --- More specific specifiers ---
String fullDate = String.format("%tA, %tB %<td, %<tY", now);
System.out.println(fullDate);
// Example Output: Friday, October 27, 2025
Prefix Meaning Example (%<tx format)
A Full weekday name Friday
B Full month name October
C 2-digit year (e.g., 20 for 2025) 20
D Equivalent to %tm/%<td/%<ty 10/27/23
F Equivalent to %tY-%<tm-%<td 2025-10-27
H Hour (00-23) 14
I Hour (01-12) 02
M Minute (00-59) 30
S Second (00-60) 05
Y 4-digit year 2025
y 2-digit year 23
m Month as a number (01-12) 10
d Day of month (01-31) 27
j Day of year (001-366) 300

Working with printf

While String.format() returns a string, System.out.printf() is its cousin. It has the exact same formatting syntax but directly prints the result to the standard output stream (System.out). This is often more convenient for console output.

int apples = 50;
int oranges = 75;
double pricePerKg = 1.99;
// Using String.format()
String report = String.format("Fruit Inventory:\nApples: %d\nOranges: %d\nPrice: $%.2f per kg", apples, oranges, pricePerKg);
System.out.println(report);
// Using System.out.printf() - more concise for printing
System.out.println("\n--- Using printf ---");
System.out.printf("Fruit Inventory:\nApples: %d\nOranges: %d\nPrice: $%.2f per kg%n", apples, oranges, pricePerKg);
// Note: %n is the recommended way to specify a newline for printf.

Complete Examples

Example 1: Formatting a User Profile

String name = "Jane Doe";
int userId = 98765;
double balance = 1250.75;
boolean isActive = true;
String profile = String.format(
    "User Profile:\n" +
    "  Name: %-20s\n" +
    "  ID: %08d\n" +
    "  Balance: $%,10.2f\n" +
    "  Status: %b",
    name, userId, balance, isActive
);
System.out.println(profile);

Output:

User Profile:
  Name: Jane Doe            
  ID: 00098765
  Balance: $  1,250.75
  Status: true

Example 2: Formatting a Log Message

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// Modern approach with java.time (Java 8+)
LocalDateTime now = LocalDateTime.now();
String timestamp = now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
String logMessage = String.format("[%s] [INFO] User 'admin' logged in from IP 192.168.1.1", timestamp);
System.out.println(logMessage);
// Example Output: [2025-10-27T14:30:05.123] [INFO] User 'admin' logged in from IP 192.168.1.1

When to Use String.format() vs. Other Methods

Method Pros Cons Best For
String.format() Very powerful, flexible, and readable. Standardized format specifiers. Can be slightly slower than simple concatenation due to parsing overhead. Complex formatting of numbers, dates, and text alignment. Logging. Generating strings for files or databases.
StringBuilder / Concatenation Fast and simple for a few variables. Becomes unreadable and error-prone with many variables. No built-in formatting (e.g., no padding, no decimal precision). Simple string construction where performance is critical and the logic is straightforward.
MessageFormat Good for internationalization (i18n). Handles complex patterns with indexed arguments ({0}, {1}). More verbose for simple cases. User-facing messages that need to be translated into different languages.
printf Identical formatting to String.format(), but prints directly. Not reusable; you can't store the formatted string. Quick and direct console output for debugging or status messages.

Summary

String.format() is an essential tool in any Java developer's toolkit. By mastering its format specifiers (%d, %f, %s, etc.) and modifiers (width, precision, flags), you can write clean, robust, and readable code for generating any kind of formatted string you need.

分享:
扫描分享到社交APP
上一篇
下一篇