The String.format() method produces formatted strings using printf-style template strings and argument lists.
Template Substitution & Precision Control: It controls decimal rounding, field width padding, thousand separators, and international locale settings. Unlike simple concat() or string addition, format() separates layout templates from runtime values. For converting non-string values to text, explore valueOf(). To measure resulting character length, see length(), or trim whitespace with trim().
Java defines two static factory overloads in java.lang.String:
// 2 Overloaded static signatures of format() in java.lang.String
public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)
| Signature | Locale Source | Description & Operational Rule |
|---|---|---|
format(String format, Object... args) |
Locale.getDefault() |
Uses the JVM's default locale. Can vary decimal separators across host systems. |
format(Locale l, String format, Object... args) |
Explicit Locale |
Guarantees consistent decimal marks (e.g. Locale.US for period separators). |
Conversion specifiers indicate the target data type to render into the template string:
String user = "Alice";
int score = 95;
char grade = 'A';
String summary = String.format("Student %s scored %d points (Grade: %c)", user, score, grade);
System.out.println(summary);Terminal Output:
Student Alice scored 95 points (Grade: A)
| Specifier | Data Type | Formatting Description |
|---|---|---|
%s / %S |
String / Object | Renders string representation (lowercase / uppercase). |
%d |
Integral Types | Decimal integer (byte, short, int, long). |
%f |
Floating-Point | Decimal floating-point number. |
%c / %C |
Character | Unicode character. |
%b / %B |
Boolean | Renders "true" or "false" based on nullity or boolean state. |
%x / %X |
Hexadecimal | Renders integer as lowercase or uppercase hex. |
%n |
None | Platform-independent line break (replaces hardcoded \n). |
%% |
None | Escaped literal percent character. |
Formatting decimal places and adding thousands grouping separators to numbers:
double balance = 12500.6789;
// Floating-point precision (%.2f rounds to 2 decimals)
System.out.println(String.format("Balance: %.2f", balance)); // 12500.68
// Comma flag (,) formats numbers with thousands separators
System.out.println(String.format("Balance: %,.2f", balance)); // 12,500.68
// Hexadecimal (%x)
System.out.println(String.format("Hex integer: %x", 255)); // ffTerminal Output:
Balance: 12500.68
Balance: 12,500.68
Hex integer: ff
Setting minimum column widths and applying zero-padding or left-alignment flags:
int id = 42;
String name = "Java";
// Width and padding flags
System.out.println(String.format("|%5d|", id)); // Right-aligned: | 42|
System.out.println(String.format("|%-5d|", id)); // Left-aligned: |42 |
System.out.println(String.format("|%05d|", id)); // Zero-padded: |00042|
System.out.println(String.format("|%-8s|", name)); // Left-aligned: |Java |Terminal Output:
| 42|
|42 |
|00042|
|Java |
The relative index flag < causes the format specifier to reuse the argument from the preceding specifier without passing it again:
String framework = "Spring";
// The '<' flag reuses the previous argument without passing it again!
String result = String.format("Framework: %s (Uppercase: %<S)", framework);
System.out.println(result);Terminal Output:
Framework: Spring (Uppercase: SPRING)
In US English, decimals use a period (.). In German and French, decimals use a comma (,):
import java.util.Locale;
double price = 1234.56;
// US Locale: dot (.) decimal and comma (,) grouping
System.out.println(String.format(Locale.US, "US: %,.2f", price)); // US: 1,234.56
// German Locale: comma (,) decimal and dot (.) grouping
System.out.println(String.format(Locale.GERMANY, "DE: %,.2f", price)); // DE: 1.234,56Terminal Output:
US: 1,234.56
DE: 1.234,56
Generating aligned text columns with fixed widths and formatted numbers:
public class TableFormatter {
public static void printRow(int id, String product, double cost) {
String row = String.format("%04d | %-12s | %,8.2f", id, product, cost);
System.out.println(row);
}
public static void main(String[] args) {
System.out.println("ID | Product | Cost ");
System.out.println("-------------------------------");
printRow(1, "Notebook", 4.50);
printRow(25, "Monitor", 289.99);
}
}Terminal Output:
ID | Product | Cost
-------------------------------
0001 | Notebook | 4.50
0025 | Monitor | 289.99
Converting raw seconds into zero-padded digital clock notation:
public class DurationFormatter {
public static String formatDuration(int totalSeconds) {
int minutes = totalSeconds / 60;
int seconds = totalSeconds % 60;
return String.format("%02d:%02d", minutes, seconds);
}
public static void main(String[] args) {
System.out.println("Track 1: " + formatDuration(65)); // 01:05
System.out.println("Track 2: " + formatDuration(210)); // 03:30
}
}Terminal Output:
Track 1: 01:05
Track 2: 03:30
Passing a floating-point number into %d (e.g. String.format("%d", 3.14)) crashes at runtime with an IllegalFormatConversionException. Always ensure specifiers match argument types.
Writing \n inside templates produces OS-specific line endings. Always use %n in format strings to ensure uniform line breaks across Windows and Linux servers.
You can compile and run this complete verification class locally in any Java IDE or environment:
import java.util.Locale;
public class StringFormatFullDemo {
public static void main(String[] args) {
String dec = String.format(Locale.US, "%.2f", 3.14159);
if (dec.equals("3.14")) {
System.out.println("Check 1 Passed: Floating-point precision rounded accurately.");
}
String padded = String.format("%04d", 7);
if (padded.equals("0007")) {
System.out.println("Check 2 Passed: Zero-padded integer width verified.");
}
String text = String.format("Welcome %s", "plus2net");
if (text.equals("Welcome plus2net")) {
System.out.println("Check 3 Passed: String placeholder substitution verified.");
}
System.out.println("All String.format() verification unit tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Floating-point precision rounded accurately.
Check 2 Passed: Zero-padded integer width verified.
Check 3 Passed: String placeholder substitution verified.
All String.format() verification unit tests passed successfully!
System.out.printf() writes directly to standard output console, while String.format() returns a formatted String object for storage or transmission.
Use %%. Because % introduces format specifiers, escaping requires doubling the character.
%n represents the platform-specific line separator (\r\n on Windows, \n on Unix/macOS), ensuring cross-platform output fidelity.
String.format() parses the format template on every call. In performance-critical tight loops, prefer StringBuilder or pre-built string concatenations.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.