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


