Is the sample on java.util.Formattable incorrect?
It is actually simple. You escape the percent characters only during formatting, not in the original property:
// apply precision
if (precision == -1 || out.length() < precision) {
// write it all
sb.append(out.replaceAll("%", "%%"));
}
else {
sb.append(out.substring(0, precision - 1).replaceAll("%", "%%")).append('*');
}
Then if you do this:
StockName stockName = new StockName("HUGE", "%Huge Fruit, Inc.", "Fruit Titanesque, Inc.");
System.out.printf("%s%n", stockName);
System.out.printf("%s%n", stockName.toString());
System.out.printf("%#s%n", stockName);
System.out.printf("%-10.8s%n", stockName);
System.out.printf("%.12s%n", stockName);
System.out.printf(Locale.FRANCE, "%25s%n", stockName);
The output looks like this:
%Huge Fruit, Inc.
HUGE - %Huge Fruit, Inc.
HUGE
HUGE
%Huge Fruit*
Fruit Titanesque, Inc.
If you want print percentage symbol %, you must escape it by double writing, e.g.
System.out.printf("%s", new StockName("PERC", "%%Company, Inc.", "Fruit Titanesque, Inc."));
this will print %Company, Inc.