Displaying Formatted Output with String.format()
1. What It Does (beginner)
String.format() builds a formatted String (doesn't print — returns!). Twin of printf (which prints). Use when you need to store/send formatted text (bill, report, log).
2. Same Specifiers, Two Uses
double pi = 3.14159;
String s = String.format("pi=%.2f", pi); // s = "pi=3.14" (stored!)
System.out.println(s); // print stored
System.out.printf("pi=%.2f%n", pi); // direct print (same output!)
// Rule: printf(format, args) = print(format(format, args))
| Spec | Example → String |
|---|---|
%d |
String.format("%d", 42) → "42" |
%.2f |
String.format("%.2f", pi) → "3.14" |
%-10s |
left-align name in 10 chars |
%05d |
zero-pad: String.format("%05d", 7) → "00007" |
%,d |
commas: String.format("%,d", 1000000) → "1,000,000" |
3. Beginner Project — Bill Line
String item = "Tea";
int qty = 2;
double price = 25.5;
String bill = String.format("%-10s %2d x %6.2f = %7.2f", item, qty, price, qty*price);
System.out.println(bill); // Tea 2 x 25.50 = 51.00
4. Traps
String.formatRETURNS (must assign/print — calling alone does nothing visible!).- Mismatch
%d← double →IllegalFormatConversionException. %%prints%:String.format("%.1f%%", 92.5)→"92.5%".
5. Exam Points
printfvsString.format(print vs return) — 5 marks, very frequent.- Bill/table program + zero-pad/commas — 5 marks, frequent.