String.format() Handbook
1. Quick Summary
String.format() is a static method that returns a formatted string using a specified format string and arguments. It is effectively the sprintf of Java.
Syntax:
String.format(String format, Object... args)Key Use: Creating readable output, aligning text in columns, and controlling decimal precision.
Localization: Use
String.format(Locale.US, ...)to ensure consistent formatting (e.g., decimal points vs commas) across different regions.
2. Anatomy of a Specifier
A format specifier follows this structure:%[argument_index$][flags][width][.precision]conversion
%: Start of specifier.flags: formatting options (e.g.,-for left-align,0for zero-pad).width: Minimum number of characters to output.precision: Max characters (strings) or decimal places (floats).conversion: The type of argument (e.g.,s,d,f).
3. Common Converters Cheat Sheet
Code | Data Type | Example Input | Example Output |
|---|---|---|---|
| String |
|
|
| Integer |
|
|
| Float/Double |
|
|
| Boolean |
|
|
| Character |
|
|
| Newline | N/A |
|
| Hexadecimal |
|
|
4. Formatting Flags
Flag | Description | Example Code | Output |
|---|---|---|---|
| Left-justify (default is right). | ` | %-5d |
| Zero-pad numbers. |
|
|
| Always show sign (+/-). |
|
|
| Grouping separator (comma). |
|
|
| Enclose negative numbers in |
|
|
5. Width & Precision Examples
Pattern | Description | Input | Result |
|---|---|---|---|
| 2 decimal places |
|
|
| Width 10, 2 decimals |
|
|
| Right-align string (width 10) |
|
|
| Left-align string (width 10) |
|
|