liveBook · Manning

Format method

As explained in 100 Java Mistakes and How to Avoid Them

String.format is a Java API method that returns a formatted string constructed from a format string and supplied arguments.

String.format constructs a string from a format string and supplied arguments. Each format specifier consumes or interprets an argument, so changing the format string without synchronizing the arguments can produce incorrect output or a runtime exception. section 6.4

Watch for these mismatches:

  • Unused arguments may be ignored: a format string containing one %d can produce “Point is: 10” even when x and y are supplied. section 6.4
  • %b accepts any object, producing true for non-null and false for null; %s accepts any type through String.valueOf(). section 6.4
  • Treat locale-sensitive formatting deliberately because the default locale can change decimal separators and other formatting behavior. section 6.11

A format string can conceal an argument-order bug

System.out.printf("Day: %s; isWeekend = %b\n",\n isWeekend, dw);\n\nThe arguments are reversed: %s receives the Boolean and %b receives the day value. Passing dw first and isWeekend second produces the intended result.

The Java compiler does not verify that format specifiers and arguments correspond. Static analysis can usually detect unused arguments and potentially exceptional formats when the format string is constant; IntelliJ IDEA provides Malformed Format String inspection, and SonarLint provides related rules. These tools may not flag every semantically wrong use, such as %b with a non-Boolean value. section 6.11 section 6.4

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains argument matching, silent unused arguments, permissive %b and %s behavior, locale effects, and static-analysis limits.
Examples
Uses point formatting, day-and-weekend output, greeting methods, and date formatting with reordered arguments.
What it assumes
Assumes Java method and argument familiarity while teaching format strings, specifiers, and their argument correspondence.
What you can do after
Diagnose mismatched format arguments and apply corrected ordering while interpreting static-analysis warnings selectively.
How it connects
Connects format strings with format specifiers, printf-style output, locales, and static analysis.

Also explained in

Compare how 3 books explain format method →

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.