Lesson Completion
Back to course

String Formatting: printf, format, and Text Blocks

Beginner
15 minutes4.7Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: Java offers powerful formatting: printf/format for placeholders, formatted() (Java 15+) as instance method, and Text Blocks (Java 15+) for multi-line strings.

When Stripe formats payment receipts: String.format("$%.2f", amount). Clean, consistent output!


2. Format Specifiers Quick Reference

SpecifierTypeExample
%sStringformat("%s", "Hi") → "Hi"
%dIntegerformat("%d", 42) → "42"
%fFloat/Doubleformat("%f", 3.14) → "3.140000"
%.2f2 decimalsformat("%.2f", 3.14159) → "3.14"
%nNewlinePlatform-specific line break
%bBooleanformat("%b", true) → "true"
%%Literal %format("100%%") → "100%"

3. Interactive & Applied Code

java
public class StringFormatting { public static void main(String[] args) { // === printf (print to console) === String name = "Alice"; int age = 25; double salary = 75000.50; System.out.printf("Name: %s%n", name); System.out.printf("Age: %d years%n", age); System.out.printf("Salary: $%.2f%n", salary); // === String.format (returns String) === String message = String.format("Hello, %s! You are %d years old.", name, age); System.out.println(message); // === WIDTH AND ALIGNMENT === System.out.printf("|%10s|%n", "Hi"); // | Hi| (right-aligned) System.out.printf("|%-10s|%n", "Hi"); // |Hi | (left-aligned) System.out.printf("|%05d|%n", 42); // |00042| (zero-padded) // === MULTIPLE VALUES === System.out.printf("%s scored %d points in %.1f minutes%n", "Player1", 100, 45.5); // === INDEXED ARGUMENTS === System.out.printf("%2$s is %1$d years old%n", 25, "Bob"); // "Bob is 25 years old" // === REAL-WORLD: Currency formatting === double price = 1234567.89; System.out.printf("Price: $%,.2f%n", price); // "Price: $1,234,567.89" // === REAL-WORLD: Table output === System.out.printf("%-15s %8s %10s%n", "Product", "Qty", "Price"); System.out.printf("%-15s %8d %10.2f%n", "Laptop", 2, 999.99); System.out.printf("%-15s %8d %10.2f%n", "Mouse", 5, 29.99); // === TEXT BLOCKS (Java 15+) === String json = """ { "name": "Alice", "age": 25, "city": "NYC" } """; System.out.println(json); String html = """ <html> <body> <h1>Hello, World!</h1> </body> </html> """; // Text blocks with formatting String template = """ Dear %s, Your order #%d has shipped. Total: $%.2f """.formatted(name, 12345, 99.99); System.out.println(template); // === formatted() method (Java 15+) === String greeting = "Hello, %s!".formatted(name); System.out.println(greeting); // "Hello, Alice!" } }

⚠️ Common Mistakes

Mistake #1: Wrong specifier type

java
System.out.printf("%d", "text"); // ❌ IllegalFormatConversionException System.out.printf("%s", "text"); // ✅

Mistake #2: Using \n instead of %n

java
printf("Line1\nLine2"); // ❌ May fail on Windows printf("Line1%nLine2"); // ✅ Platform-independent

4. The "Interview Corner"

🏆 Q1: "printf vs format()?" Answer: printf prints to console, format returns String. Same format specifiers.

🏆 Q2: "What are Text Blocks for?" Answer: Multi-line strings (JSON, HTML, SQL) without escape sequences. Preserves indentation, cleaner code.


🎓 Key Takeaways

%s string, %d int, %f float, %.2f 2 decimals
%n for platform-independent newlines
✅ Text blocks """...""" for multi-line (Java 15+)
formatted() as instance method (Java 15+)
✅ Width and padding for aligned tables

Topics Covered

Java FundamentalsStrings

Tags

#java#strings#string-manipulation#string-methods#beginner-friendly

Last Updated

2025-02-01