Lesson 5 of 10
String Formatting - printf, format, formatted
Proper string formatting produces clean, readable output - important for reports, logs, CLI tools, and user messages. Java provides printf-style formatting via String.format(), System.out.printf(), and (Java 15+) the formatted() instance method.
Format Specifiers
public class Formatting {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
double price = 1234.5678;
long count = 1_500_000L;
// String.format - returns formatted String
String greeting = String.format("Name: %-10s | Age: %3d", name, age);
System.out.println(greeting);
// Name: Alice | Age: 30
// %-10s = left-aligned in 10 chars; %3d = right-aligned in 3 chars
// printf - prints directly (no newline by default, use %n or \n)
System.out.printf("Price: $%,.2f%n", price); // Price: $1,234.57 (comma separator)
System.out.printf("Count: %,d%n", count); // Count: 1,500,000
System.out.printf("Hex: %x | Oct: %o%n", 255, 255); // Hex: ff | Oct: 377
System.out.printf("Sci: %e%n", price); // Sci: 1.234568e+03
System.out.printf("Bool: %b%n", null); // Bool: false (null = false)
// Java 15+ - formatted() instance method
String report = "Item: %s, Price: $%.2f, Stock: %d"
.formatted("Laptop", 999.99, 42);
System.out.println(report); // Item: Laptop, Price: $999.99, Stock: 42
// Padding and alignment
System.out.printf("%-20s %8.2f%n", "Clean Code", 39.99); // left pad title, right pad price
System.out.printf("%-20s %8.2f%n", "Effective Java", 44.99);
// %n vs \n: %n uses OS line separator (\r\n on Windows, \n on Linux)
// Prefer %n in printf for portability
}
}Quick Quiz
Tip
Tip
Practice String Formatting printf format formatted in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for String Formatting - printf, format, formatted
Practice Task
Note
Practice Task - (1) Write a working example of String Formatting printf format formatted from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with String Formatting printf format formatted is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?