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, 0 for 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

%s

String

"Java"

"Java"

%d

Integer

100

"100"

%f

Float/Double

3.14159

"3.141590"

%b

Boolean

true

"true"

%c

Character

'A'

"A"

%n

Newline

N/A

\n (Platform specific)

%x

Hexadecimal

255

"ff"

4. Formatting Flags

Flag

Description

Example Code

Output

-

Left-justify (default is right).

`

%-5d

0

Zero-pad numbers.

%05d

00042

+

Always show sign (+/-).

%+d

+15

,

Grouping separator (comma).

%,d

1,000,000

(

Enclose negative numbers in ().

%(d

(50)

5. Width & Precision Examples

Pattern

Description

Input

Result

%.2f

2 decimal places

3.14159

3.14

%10.2f

Width 10, 2 decimals

3.14159

3.14

%10s

Right-align string (width 10)

"Hi"

Hi

%-10s

Left-align string (width 10)

"Hi"

Hi

← Back to Learning Journey