liveBook · Manning

Format string

As explained in 100 Java Mistakes and How to Avoid Them

A format string is a string containing directives that specify how values or text should be interpreted or formatted.

A format string contains directives that control how subsequent arguments are interpreted and rendered. Java’s String.format() and PrintStream.printf() use format specifiers to substitute values into the string. section 6.4

Treat mismatched format arguments as a practical correctness and reliability hazard:

  • Update the arguments whenever the format string changes; unused arguments may be silently ignored, while incompatible arguments can produce incorrectly formatted output or runtime exceptions. section 6.4
  • Do not assume every specifier enforces the intended type: %s accepts any value, and %b converts non-Boolean values to true when non-null and false when null. section 6.4
  • Use static analysis when the format string is constant; IntelliJ IDEA and SonarLint can detect several mismatches, but may not flag semantically wrong uses such as %b with a non-Boolean. section 6.11 section 6.4

Argument order changes the meaning

With int x = 10 and int y = 20, System.out.printf("Point is: %d\n", x, y); prints only Point is: 10 because the extra argument is ignored. For typed values, align each argument with its directive: System.out.printf("Day: %s; isWeekend = %b\n", dw, isWeekend);. section 6.4

int x = 10;
int y = 20;
System.out.printf("Point is: %d\n", x, y);

Inspect the minimal example where an unused argument produces plausible but incomplete output. section 6.4

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains specifier substitution, silent unused arguments, permissive %s and %b behavior, and static-analysis limits.
Examples
Uses point output, weekday and weekend status, greeting methods, and intentionally mismatched printf calls.
What it assumes
Assumes Java method-call and type knowledge while teaching format-specifier substitution and common argument mismatches.
What you can do after
Diagnose/debug with it by aligning directives and arguments, checking permissive specifiers, and enabling targeted inspections.
How it connects
Connects format specifiers with argument ordering, runtime exceptions, static analysis, and locale-sensitive formatting.

Also explained in

Compare how 5 books explain format string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.