Formatted Printing with System.out.printf & Format Specifiers
1Concept
System.out.printf() writes formatted strings to the console using format specifiers like %d (decimal int), %s (string), %f (float/double), %c (char), %b (boolean), and %n (platform-independent newline). Width flags and precision controls allow clean tabular outputs.
2Architecture Diagram
Format String: "| %-15s | %10.2f | %4d |%n"
| | |
Left-align 2 Decimals 4-digit width3Code Example
Core Java
public class PrintfDemo {
public static void main(String[] args) {
System.out.println("+-----------------+------------+------+");
System.out.println("| PRODUCT | PRICE ($) | QTY |");
System.out.println("+-----------------+------------+------+");
String item1 = "Cloud Server";
double price1 = 129.95;
int qty1 = 4;
System.out.printf("| %-15s | %10.2f | %4d |%n", item1, price1, qty1);
String item2 = "PostgreSQL DB";
double price2 = 249.50;
int qty2 = 2;
System.out.printf("| %-15s | %10.2f | %4d |%n", item2, price2, qty2);
System.out.println("+-----------------+------------+------+");
}
}4Expected Output
+-----------------+------------+------+ | PRODUCT | PRICE ($) | QTY | +-----------------+------------+------+ | Cloud Server | 129.95 | 4 | | PostgreSQL DB | 249.50 | 2 | +-----------------+------------+------+
5Key Takeaways
- ✓Always use %n instead of \n in printf for cross-platform newline compatibility (Windows uses \r\n, Linux uses \n).
- ✓String.format() uses identical format syntax but returns a String instead of writing to console.
- ✓Negative width flag (e.g. %-15s) left-aligns text; positive right-aligns.