String Processing
String Format
When building reports, logs, or user-facing messages, you need precise control over how data appears. String formatting creates aligned columns, fixed decimal places, reusable templates, and consistent spacing.
Basic Format Specifiers
Basics.java
Replay: real traced execution (multi-file project)
// Basic format specifiers
public class Basics {
public static void main(String[] args) {
// String
String name = "Alice";
String greeting = String.format("Hello, %s!", name);
System.out.println(greeting);
// Integer
int age = 25;
String ageStr = String.format("Age: %d", age);
System.out.println(ageStr);
// Float
double price = 19.99;
String priceStr = String.format("Price: $%f", price);
System.out.println(priceStr);
// Multiple arguments
String msg = String.format("%s is %d years old and has $%.2f",
name, age, price);
System.out.println(msg);
// Direct printing with printf
System.out.printf("Name: %s, Age: %d%n", "Bob", 30);
// Different types
String formatted = String.format(
"String: %s, Int: %d, Float: %.2f, Boolean: %b",
"test", 42, 3.14159, true
);
System.out.println(formatted);
}
}
// Basic format specifiers
public class Basics {
public static void main(String[] args) {
// String
String name = "Mina";
String greeting = String.format("Hello, %s!", name);
System.out.println(greeting);
// Integer
int age = 25;
String ageStr = String.format("Age: %d", age);
System.out.println(ageStr);
// Float
double price = 19.99;
String priceStr = String.format("Price: $%f", price);
System.out.println(priceStr);
// Multiple arguments
String msg = String.format("%s is %d years old and has $%.2f",
name, age, price);
System.out.println(msg);
// Direct printing with printf
System.out.printf("Name: %s, Age: %d%n", "Bob", 30);
// Different types
String formatted = String.format(
"String: %s, Int: %d, Float: %.2f, Boolean: %b",
"test", 42, 3.14159, true
);
System.out.println(formatted);
}
}
// Basic format specifiers
public class Basics {
public static void main(String[] args) {
// String
String name = "Alice";
String greeting = String.format("Hello, %s!", name);
System.out.println(greeting);
// Integer
int age = 25;
String ageStr = String.format("Age: %d", age);
System.out.println(ageStr);
// Float
double price = 7.5;
String priceStr = String.format("Price: $%f", price);
System.out.println(priceStr);
// Multiple arguments
String msg = String.format("%s is %d years old and has $%.2f",
name, age, price);
System.out.println(msg);
// Direct printing with printf
System.out.printf("Name: %s, Age: %d%n", "Bob", 30);
// Different types
String formatted = String.format(
"String: %s, Int: %d, Float: %.2f, Boolean: %b",
"test", 42, 3.14159, true
);
System.out.println(formatted);
}
}
name ← Alice, greeting ← Hello, Alice!, age ← 25, ageStr ← Age: 25
5public static void main(String[] args) {6 // String7 String name→ Alice = "Alice"; //@name="Alice", "Mina"8 String greeting→ Hello, Alice! = String.format("Hello, %s!", nameAlice);9 System.out.println(greetingHello, Alice!);1011 // Integer12 int age→ 25 = 25;13 String ageStr→ Age: 25 = String.format("Age: %d", age25);14 System.out.println(ageStrAge: 25);1516 // Float17 double price→ 19.99 = 19.99; //@price=19.99, 7.518 String priceStr→ Price: $19.990000 = String.format("Price: $%f", price19.99);19 System.out.println(priceStrPrice: $19.990000);2021 // Multiple arguments22 String msg→ Alice is 25 years old and has $19.99 = String.format("%s is %d years old and has $%.2f", 23 nameAlice, age25, price19.99);24 System.out.println(msgAlice is 25 years old and has $19.99);2526 // Direct printing with printf27 System.out.printf("Name: %s, Age: %d%n", "Bob", 30);2829 // Different types30 String formatted→ String: test, Int: 42, Float: 3.14, Boolean: true = String.format(31 "String: %s, Int: %d, Float: %.2f, Boolean: %b",32 "test", 42, 3.14159, true33 );34 System.out.println(formattedString: test, Int: 42, Float: 3.14, Boolean: true);35}outputHello, Alice! Age: 25 Price: $19.990000 Alice is 25 years old and has $19.99 String: test, Int: 42, Float: 3.14, Boolean: true
name ← Mina, greeting ← Hello, Mina!, age ← 25, ageStr ← Age: 25
5public static void main(String[] args) {6 // String7 String name→ Mina = "Mina";8 String greeting→ Hello, Mina! = String.format("Hello, %s!", nameMina);9 System.out.println(greetingHello, Mina!);1011 // Integer12 int age→ 25 = 25;13 String ageStr→ Age: 25 = String.format("Age: %d", age25);14 System.out.println(ageStrAge: 25);1516 // Float17 double price→ 19.99 = 19.99;18 String priceStr→ Price: $19.990000 = String.format("Price: $%f", price19.99);19 System.out.println(priceStrPrice: $19.990000);2021 // Multiple arguments22 String msg→ Mina is 25 years old and has $19.99 = String.format("%s is %d years old and has $%.2f", 23 nameMina, age25, price19.99);24 System.out.println(msgMina is 25 years old and has $19.99);2526 // Direct printing with printf27 System.out.printf("Name: %s, Age: %d%n", "Bob", 30);2829 // Different types30 String formatted→ String: test, Int: 42, Float: 3.14, Boolean: true = String.format(31 "String: %s, Int: %d, Float: %.2f, Boolean: %b",32 "test", 42, 3.14159, true33 );34 System.out.println(formattedString: test, Int: 42, Float: 3.14, Boolean: true);35}outputHello, Mina! Age: 25 Price: $19.990000 Mina is 25 years old and has $19.99 String: test, Int: 42, Float: 3.14, Boolean: true
name ← Alice, greeting ← Hello, Alice!, age ← 25, ageStr ← Age: 25
5public static void main(String[] args) {6 // String7 String name→ Alice = "Alice";8 String greeting→ Hello, Alice! = String.format("Hello, %s!", nameAlice);9 System.out.println(greetingHello, Alice!);1011 // Integer12 int age→ 25 = 25;13 String ageStr→ Age: 25 = String.format("Age: %d", age25);14 System.out.println(ageStrAge: 25);1516 // Float17 double price→ 7.5 = 7.5;18 String priceStr→ Price: $7.500000 = String.format("Price: $%f", price7.5);19 System.out.println(priceStrPrice: $7.500000);2021 // Multiple arguments22 String msg→ Alice is 25 years old and has $7.50 = String.format("%s is %d years old and has $%.2f", 23 nameAlice, age25, price7.5);24 System.out.println(msgAlice is 25 years old and has $7.50);2526 // Direct printing with printf27 System.out.printf("Name: %s, Age: %d%n", "Bob", 30);2829 // Different types30 String formatted→ String: test, Int: 42, Float: 3.14, Boolean: true = String.format(31 "String: %s, Int: %d, Float: %.2f, Boolean: %b",32 "test", 42, 3.14159, true33 );34 System.out.println(formattedString: test, Int: 42, Float: 3.14, Boolean: true);35}outputHello, Alice! Age: 25 Price: $7.500000 Alice is 25 years old and has $7.50 String: test, Int: 42, Float: 3.14, Boolean: true
format_specifier
A placeholder like %s, %d, or %.2f that gets replaced with an argument value during formatting.
Width and Precision
Width controls minimum output size. Precision controls digits after the decimal point for floating-point output.
WidthPrecision.java
Replay: real traced execution (multi-file project)
// Width and precision
public class WidthPrecision {
public static void main(String[] args) {
// Minimum width
System.out.println(String.format("|%10s|", "Hello"));
System.out.println(String.format("|%10s|", "Hi"));
// Left align with -
System.out.println(String.format("|%-10s|", "Hello"));
System.out.println(String.format("|%-10s|", "Hi"));
// Right align integers
System.out.println(String.format("|%5d|", 42));
System.out.println(String.format("|%5d|", 12345));
// Zero padding
System.out.println(String.format("%05d", 42));
System.out.println(String.format("%08d", 123));
// Precision for floats
double pi = 3.14159265359;
System.out.println("\nPrecision examples:");
System.out.println(String.format("%.2f", pi)); // 2 decimals
System.out.println(String.format("%.4f", pi)); // 4 decimals
System.out.println(String.format("%.0f", pi)); // 0 decimals
// Width and precision combined
System.out.println("\nWidth + Precision:");
System.out.println(String.format("|%10.2f|", pi));
System.out.println(String.format("|%10.4f|", 1.5));
// Table formatting
System.out.println("\nTable:");
System.out.printf("%-10s %5s %8s%n", "Name", "Age", "Score");
System.out.printf("%-10s %5d %8.2f%n", "Alice", 25, 95.5);
System.out.printf("%-10s %5d %8.2f%n", "Bob", 30, 87.25);
System.out.printf("%-10s %5d %8.2f%n", "Charlie", 22, 92.0);
}
}
// Width and precision
public class WidthPrecision {
public static void main(String[] args) {
// Minimum width
System.out.println(String.format("|%10s|", "Hello"));
System.out.println(String.format("|%10s|", "Hi"));
// Left align with -
System.out.println(String.format("|%-10s|", "Hello"));
System.out.println(String.format("|%-10s|", "Hi"));
// Right align integers
System.out.println(String.format("|%5d|", 42));
System.out.println(String.format("|%5d|", 12345));
// Zero padding
System.out.println(String.format("%05d", 42));
System.out.println(String.format("%08d", 123));
// Precision for floats
double pi = 2.718281828;
System.out.println("\nPrecision examples:");
System.out.println(String.format("%.2f", pi)); // 2 decimals
System.out.println(String.format("%.4f", pi)); // 4 decimals
System.out.println(String.format("%.0f", pi)); // 0 decimals
// Width and precision combined
System.out.println("\nWidth + Precision:");
System.out.println(String.format("|%10.2f|", pi));
System.out.println(String.format("|%10.4f|", 1.5));
// Table formatting
System.out.println("\nTable:");
System.out.printf("%-10s %5s %8s%n", "Name", "Age", "Score");
System.out.printf("%-10s %5d %8.2f%n", "Alice", 25, 95.5);
System.out.printf("%-10s %5d %8.2f%n", "Bob", 30, 87.25);
System.out.printf("%-10s %5d %8.2f%n", "Charlie", 22, 92.0);
}
}
pi ← 3.14159265359
5public static void main(String[] args) {6 // Minimum width7 System.out.println(String.format("|%10s|", "Hello"));8 System.out.println(String.format("|%10s|", "Hi"));910 // Left align with -11 System.out.println(String.format("|%-10s|", "Hello"));12 System.out.println(String.format("|%-10s|", "Hi"));1314 // Right align integers15 System.out.println(String.format("|%5d|", 42));16 System.out.println(String.format("|%5d|", 12345));1718 // Zero padding19 System.out.println(String.format("%05d", 42));20 System.out.println(String.format("%08d", 123));2122 // Precision for floats23 double pi→ 3.14159265359 = 3.14159265359; //@pi=3.14159265359, 2.71828182824 System.out.println("\nPrecision examples:");25 System.out.println(String.format("%.2f", pi3.14159265359)); // 2 decimals26 System.out.println(String.format("%.4f", pi3.14159265359)); // 4 decimals27 System.out.println(String.format("%.0f", pi3.14159265359)); // 0 decimals2829 // Width and precision combined30 System.out.println("\nWidth + Precision:");31 System.out.println(String.format("|%10.2f|", pi3.14159265359));32 System.out.println(String.format("|%10.4f|", 1.5));3334 // Table formatting35 System.out.println("\nTable:");36 System.out.printf("%-10s %5s %8s%n", "Name", "Age", "Score");37 System.out.printf("%-10s %5d %8.2f%n", "Alice", 25, 95.5);38 System.out.printf("%-10s %5d %8.2f%n", "Bob", 30, 87.25);39 System.out.printf("%-10s %5d %8.2f%n", "Charlie", 22, 92.0);40}output| Hello| | Hi| |Hello | |Hi | | 42| |12345| 00042 00000123 Precision examples: 3.14 3.1416 3 Width + Precision: | 3.14| | 1.5000| Table:
pi ← 2.718281828
5public static void main(String[] args) {6 // Minimum width7 System.out.println(String.format("|%10s|", "Hello"));8 System.out.println(String.format("|%10s|", "Hi"));910 // Left align with -11 System.out.println(String.format("|%-10s|", "Hello"));12 System.out.println(String.format("|%-10s|", "Hi"));1314 // Right align integers15 System.out.println(String.format("|%5d|", 42));16 System.out.println(String.format("|%5d|", 12345));1718 // Zero padding19 System.out.println(String.format("%05d", 42));20 System.out.println(String.format("%08d", 123));2122 // Precision for floats23 double pi→ 2.718281828 = 2.718281828;24 System.out.println("\nPrecision examples:");25 System.out.println(String.format("%.2f", pi2.718281828)); // 2 decimals26 System.out.println(String.format("%.4f", pi2.718281828)); // 4 decimals27 System.out.println(String.format("%.0f", pi2.718281828)); // 0 decimals2829 // Width and precision combined30 System.out.println("\nWidth + Precision:");31 System.out.println(String.format("|%10.2f|", pi2.718281828));32 System.out.println(String.format("|%10.4f|", 1.5));3334 // Table formatting35 System.out.println("\nTable:");36 System.out.printf("%-10s %5s %8s%n", "Name", "Age", "Score");37 System.out.printf("%-10s %5d %8.2f%n", "Alice", 25, 95.5);38 System.out.printf("%-10s %5d %8.2f%n", "Bob", 30, 87.25);39 System.out.printf("%-10s %5d %8.2f%n", "Charlie", 22, 92.0);40}output| Hello| | Hi| |Hello | |Hi | | 42| |12345| 00042 00000123 Precision examples: 2.72 2.7183 3 Width + Precision: | 2.72| | 1.5000| Table:
width
The minimum number of characters used for a formatted value, padding with spaces if needed.
precision
For floating-point numbers, the number of digits shown after the decimal point.
printf Output
printf writes formatted output directly instead of first creating a String.
Printf.java
Replay: real traced execution (multi-file project)
// Printf style formatting
public class Printf {
public static void main(String[] args) {
// printf prints directly (no assignment)
System.out.printf("Hello, %s!%n", "World");
// Format and print in one call
String name = "Alice";
int age = 25;
double salary = 75000.50;
System.out.printf("Employee: %s%n", name);
System.out.printf("Age: %d years%n", age);
System.out.printf("Salary: $%.2f%n", salary);
// Multiple values in one printf
System.out.printf("%n%s is %d years old and earns $%.2f%n",
name, age, salary);
// Formatting numbers
System.out.println("\nNumber formats:");
System.out.printf("Decimal: %d%n", 42);
System.out.printf("Hex: %x%n", 255);
System.out.printf("Octal: %o%n", 8);
System.out.printf("Scientific: %e%n", 12345.6789);
// Signs
System.out.println("\nSigns:");
System.out.printf("Positive with +: %+d%n", 42);
System.out.printf("Negative: %+d%n", -42);
System.out.printf("Space for positive: % d%n", 42);
// Grouping separator
System.out.println("\nGrouping:");
System.out.printf("Large number: %,d%n", 1234567890);
System.out.printf("Float grouped: %,.2f%n", 1234567.89);
// Report example
System.out.println("\n=== Sales Report ===");
System.out.printf("%-15s: %,10d%n", "Units Sold", 1250);
System.out.printf("%-15s: $%,10.2f%n", "Revenue", 125000.75);
System.out.printf("%-15s: $%,10.2f%n", "Profit", 45000.25);
}
}
name ← Alice, age ← 25, salary ← 75000.5
5public static void main(String[] args) {6 // printf prints directly (no assignment)7 System.out.printf("Hello, %s!%n", "World");89 // Format and print in one call10 String name→ Alice = "Alice";11 int age→ 25 = 25;12 double salary→ 75000.5 = 75000.50;1314 System.out.printf("Employee: %s%n", nameAlice);15 System.out.printf("Age: %d years%n", age25);16 System.out.printf("Salary: $%.2f%n", salary75000.5);1718 // Multiple values in one printf19 System.out.printf("%n%s is %d years old and earns $%.2f%n", 20 nameAlice, age25, salary75000.5);2122 // Formatting numbers23 System.out.println("\nNumber formats:");24 System.out.printf("Decimal: %d%n", 42);25 System.out.printf("Hex: %x%n", 255);26 System.out.printf("Octal: %o%n", 8);27 System.out.printf("Scientific: %e%n", 12345.6789);2829 // Signs30 System.out.println("\nSigns:");31 System.out.printf("Positive with +: %+d%n", 42);32 System.out.printf("Negative: %+d%n", -42);33 System.out.printf("Space for positive: % d%n", 42);3435 // Grouping separator36 System.out.println("\nGrouping:");37 System.out.printf("Large number: %,d%n", 1234567890);38 System.out.printf("Float grouped: %,.2f%n", 1234567.89);3940 // Report example41 System.out.println("\n=== Sales Report ===");42 System.out.printf("%-15s: %,10d%n", "Units Sold", 1250);43 System.out.printf("%-15s: $%,10.2f%n", "Revenue", 125000.75);44 System.out.printf("%-15s: $%,10.2f%n", "Profit", 45000.25);45}output Number formats: Signs: Grouping: === Sales Report ===
Argument Index
ArgumentIndex.java
Replay: real traced execution (multi-file project)
// Argument index
public class ArgumentIndex {
public static void main(String[] args) {
// Reuse arguments with index
String msg1 = String.format("%1$s has %2$d apples. %1$s likes apples.",
"Alice", 5);
System.out.println(msg1);
// Reverse order
String msg2 = String.format("%2$s %1$s", "World", "Hello");
System.out.println(msg2);
// Date formatting with index
int year = 2025, month = 1, day = 29;
String date1 = String.format("%1$d-%2$02d-%3$02d", year, month, day);
String date2 = String.format("%2$02d/%3$02d/%1$d", year, month, day);
System.out.println("\nDate formats:");
System.out.println("ISO: " + date1);
System.out.println("US: " + date2);
// Same value, different formats
double value = 1234.567;
String formatted = String.format(
"As is: %1$f, Rounded: %1$.2f, Scientific: %1$e",
value
);
System.out.println("\n" + formatted);
// Locale-specific formatting
String msg3 = String.format(
"%1$s costs $%2$.2f. Buy %3$d %1$s for $%4$.2f",
"Apple", 1.50, 10, 15.00
);
System.out.println("\n" + msg3);
}
}
msg1 ← Alice has 5 apples. Alice likes apples., msg2 ← Hello World
5public static void main(String[] args) {6 // Reuse arguments with index7 String msg1→ Alice has 5 apples. Alice likes apples. = String.format("%1$s has %2$d apples. %1$s likes apples.",8 "Alice", 5);9 System.out.println(msg1Alice has 5 apples. Alice likes apples.);1011 // Reverse order12 String msg2→ Hello World = String.format("%2$s %1$s", "World", "Hello");13 System.out.println(msg2Hello World);1415 // Date formatting with index16 int year = 2025, month = 1, day→ 29 = 29;17 String date1→ 2025-01-29 = String.format("%1$d-%2$02d-%3$02d", year2025, month1, day29);18 String date2→ 01/29/2025 = String.format("%2$02d/%3$02d/%1$d", year2025, month1, day29);1920 System.out.println("\nDate formats:");21 System.out.println("ISO: " + date12025-01-29);22 System.out.println("US: " + date201/29/2025);2324 // Same value, different formats25 double value→ 1234.567 = 1234.567;26 String formatted→ As is: 1234.567000, Rounded: 1234.57, Scientific: 1.234567e+03 = String.format(27 "As is: %1$f, Rounded: %1$.2f, Scientific: %1$e",28 value1234.56729 );30 System.out.println("\n" + formattedAs is: 1234.567000, Rounded: 1234.57, Scientific: 1.234567e+03);3132 // Locale-specific formatting33 String msg3→ Apple costs $1.50. Buy 10 Apple for $15.00 = String.format(34 "%1$s costs $%2$.2f. Buy %3$d %1$s for $%4$.2f",35 "Apple", 1.50, 10, 15.0036 );37 System.out.println("\n" + msg3Apple costs $1.50. Buy 10 Apple for $15.00);38}outputAlice has 5 apples. Alice likes apples. Hello World Date formats: ISO: 2025-01-29 US: 01/29/2025 As is: 1234.567000, Rounded: 1234.57, Scientific: 1.234567e+03 Apple costs $1.50. Buy 10 Apple for $15.00
argument_index
The %n$ syntax references arguments by position, allowing the same value to be reused or reordered.
Text Blocks
Java text blocks make multi-line templates easier to read before formatting them.
TextBlocks.java
Replay: real traced execution (multi-file project)
// Text blocks (Java 15+)
public class TextBlocks {
public static void main(String[] args) {
// Text block (preserves formatting)
String json = """
{
"name": "Alice",
"age": 25,
"city": "New York"
}
""";
System.out.println(json);
// Text block with formatting
String name = "Bob";
int age = 30;
String jsonFormatted = """
{
"name": "%s",
"age": %d,
"active": true
}
""".formatted(name, age);
System.out.println(jsonFormatted);
// HTML template
String title = "Welcome";
String content = "This is a text block example.";
String html = """
<html>
<head>
<title>%s</title>
</head>
<body>
<h1>%s</h1>
<p>%s</p>
</body>
</html>
""".formatted(title, title, content);
System.out.println(html);
// SQL query
String table = "users";
String condition = "age > 21";
String sql = """
SELECT *
FROM %s
WHERE %s
ORDER BY name;
""".formatted(table, condition);
System.out.println(sql);
// Table with alignment
String[][] data = {
{"Alice", "25", "Engineer"},
{"Bob", "30", "Designer"},
{"Charlie", "35", "Manager"}
};
System.out.println("\nEmployee Table:");
System.out.printf("%-10s %-5s %-12s%n", "Name", "Age", "Title");
System.out.println("-".repeat(30));
for (String[] row : data) {
System.out.printf("%-10s %-5s %-12s%n", row[0], row[1], row[2]);
}
}
}
json ← { "name": "Alice", "age": 25, "city": "New York" }
5public static void main(String[] args) {6 // Text block (preserves formatting)7 String json→ { "name": "Alice", "age": 25, "city": "New York" } = """8 {9 "name": "Alice",10 "age": 25,11 "city": "New York"12 }13 """;14 System.out.println(json{ "name": "Alice", "age": 25, "city": "New York" } );1516 // Text block with formatting17 String name→ Bob = "Bob";18 int age→ 30 = 30;1920 String jsonFormatted→ { "name": "Bob", "age": 30, "active": true } = """21 {22 "name": "%s",23 "age": %d,24 "active": true25 }26 """.formatted(nameBob, age30);27 System.out.println(jsonFormatted{ "name": "Bob", "age": 30, "active": true } );2829 // HTML template30 String title→ Welcome = "Welcome";31 String content→ This is a text block example. = "This is a text block example.";3233 String html→ <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome</h1> <p>This is a text block example.</p> </body> </html> = """34 <html>35 <head>36 <title>%s</title>37 </head>38 <body>39 <h1>%s</h1>40 <p>%s</p>41 </body>42 </html>43 """.formatted(titleWelcome, title, contentThis is a text block example.);44 System.out.println(html<html> <head> <title>Welcome</title> </head> <body> <h1>Welcome</h1> <p>This is a text block example.</p> </body> </html> );4546 // SQL query47 String table→ users = "users";48 String condition→ age > 21 = "age > 21";4950 String sql→ SELECT * FROM users WHERE age > 21 ORDER BY name; = """51 SELECT *52 FROM %s53 WHERE %s54 ORDER BY name;55 """.formatted(tableusers, conditionage > 21);56 System.out.println(sqlSELECT * FROM users WHERE age > 21 ORDER BY name; );5758 // Table with alignment59 String[][] data = {60 {"Alice", "25", "Engineer"},61 {"Bob", "30", "Designer"},62 {"Charlie", "35", "Manager"}63 };6465 System.out.println("\nEmployee Table:");66 System.out.printf("%-10s %-5s %-12s%n", "Name", "Age", "Title");67 System.out.println("-".repeat(30));68 for (String[] row : data) {output{ "name": "Alice", "age": 25, "city": "New York" } { "name": "Bob", "age": 30, "active": true } <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome</h1> <p>This is a text block example.</p> </body> </html> SELECT * FROM users WHERE age > 21 ORDER BY name; Employee Table: ------------------------------for (String[] row : data)
pass 1 of 367System.out.println("-".repeat(30));68for (String[] row : data) {69 System.out.printf("%-10s %-5s %-12s%n", row[0]Alice, row[1]25, row[2]Engineer);70}All 3 passes — pass 1 is the card above pass row[0]row[1]row[2]1 Alice 25 Engineer 2 Bob 30 Designer 3 Charlie 35 Manager
Practical Formatting
Formatting is commonly used for reports, logs, progress displays, and aligned statistics.
Practical.java
Replay: real traced execution (multi-file project)
// Practical formatting examples
public class Practical {
public static void printInvoice(String customer, String[][] items) {
System.out.println("=".repeat(50));
System.out.printf("INVOICE FOR: %s%n", customer);
System.out.println("=".repeat(50));
System.out.printf("%-20s %8s %10s %12s%n",
"Item", "Qty", "Price", "Total");
System.out.println("-".repeat(50));
double grandTotal = 0;
for (String[] item : items) {
String name = item[0];
int qty = Integer.parseInt(item[1]);
double price = Double.parseDouble(item[2]);
double total = qty * price;
grandTotal += total;
System.out.printf("%-20s %8d $%9.2f $%11.2f%n",
name, qty, price, total);
}
System.out.println("-".repeat(50));
System.out.printf("%41s $%11.2f%n", "GRAND TOTAL:", grandTotal);
System.out.println("=".repeat(50));
}
public static void printProgress(String task, int percent) {
int barWidth = 30;
int filled = (int) (barWidth * percent / 100.0);
String bar = "█".repeat(filled) + "░".repeat(barWidth - filled);
System.out.printf("\r%-20s [%s] %3d%%", task, bar, percent);
}
public static void log(String level, String message) {
long timestamp = 1706500800000L;
String formatted = String.format("[%d] %-7s: %s",
timestamp, level, message);
System.out.println(formatted);
}
public static void printStatistics(String[] labels, double[] values) {
System.out.println("\nStatistics:");
System.out.println("-".repeat(30));
for (int i = 0; i < labels.length; i++) {
System.out.printf("%-15s: %12.2f%n", labels[i], values[i]);
}
}
public static void main(String[] args) {
// Invoice
String[][] items = {
{"Widget A", "5", "19.99"},
{"Widget B", "3", "29.99"},
{"Widget C", "10", "9.99"}
};
String customer = "John Doe";
printInvoice(customer, items);
// Progress bars
System.out.println("\n\nProgress Demo:");
printProgress("Downloading", 0);
printProgress("Downloading", 50);
printProgress("Downloading", 100);
System.out.println();
// Logs
System.out.println("\nLog Entries:");
log("INFO", "Application started");
log("WARNING", "Low memory");
log("ERROR", "Connection failed");
// Statistics
String[] statLabels = {"Mean", "Median", "Std Dev", "Min", "Max"};
double[] statValues = {75.5, 72.0, 12.3, 45.0, 98.0};
printStatistics(statLabels, statValues);
}
}
// Practical formatting examples
public class Practical {
public static void printInvoice(String customer, String[][] items) {
System.out.println("=".repeat(50));
System.out.printf("INVOICE FOR: %s%n", customer);
System.out.println("=".repeat(50));
System.out.printf("%-20s %8s %10s %12s%n",
"Item", "Qty", "Price", "Total");
System.out.println("-".repeat(50));
double grandTotal = 0;
for (String[] item : items) {
String name = item[0];
int qty = Integer.parseInt(item[1]);
double price = Double.parseDouble(item[2]);
double total = qty * price;
grandTotal += total;
System.out.printf("%-20s %8d $%9.2f $%11.2f%n",
name, qty, price, total);
}
System.out.println("-".repeat(50));
System.out.printf("%41s $%11.2f%n", "GRAND TOTAL:", grandTotal);
System.out.println("=".repeat(50));
}
public static void printProgress(String task, int percent) {
int barWidth = 30;
int filled = (int) (barWidth * percent / 100.0);
String bar = "█".repeat(filled) + "░".repeat(barWidth - filled);
System.out.printf("\r%-20s [%s] %3d%%", task, bar, percent);
}
public static void log(String level, String message) {
long timestamp = 1706500800000L;
String formatted = String.format("[%d] %-7s: %s",
timestamp, level, message);
System.out.println(formatted);
}
public static void printStatistics(String[] labels, double[] values) {
System.out.println("\nStatistics:");
System.out.println("-".repeat(30));
for (int i = 0; i < labels.length; i++) {
System.out.printf("%-15s: %12.2f%n", labels[i], values[i]);
}
}
public static void main(String[] args) {
// Invoice
String[][] items = {
{"Widget A", "5", "19.99"},
{"Widget B", "3", "29.99"},
{"Widget C", "10", "9.99"}
};
String customer = "Ada Lovelace";
printInvoice(customer, items);
// Progress bars
System.out.println("\n\nProgress Demo:");
printProgress("Downloading", 0);
printProgress("Downloading", 50);
printProgress("Downloading", 100);
System.out.println();
// Logs
System.out.println("\nLog Entries:");
log("INFO", "Application started");
log("WARNING", "Low memory");
log("ERROR", "Connection failed");
// Statistics
String[] statLabels = {"Mean", "Median", "Std Dev", "Min", "Max"};
double[] statValues = {75.5, 72.0, 12.3, 45.0, 98.0};
printStatistics(statLabels, statValues);
}
}
customer ← John Doe
53public static void main(String[] args) {54 // Invoice55 String[][] items = {56 {"Widget A", "5", "19.99"},57 {"Widget B", "3", "29.99"},58 {"Widget C", "10", "9.99"}59 };60 String customer→ John Doe = "John Doe"; //@customer="John Doe", "Ada Lovelace"61 printInvoice(customerJohn Doe, items);grandTotal ← 0.0
5public static void printInvoice(String customerJohn Doe, String[][] items) {6 System.out.println("=".repeat(50));7 System.out.printf("INVOICE FOR: %s%n", customerJohn Doe);8 System.out.println("=".repeat(50));9 System.out.printf("%-20s %8s %10s %12s%n", 10 "Item", "Qty", "Price", "Total");11 System.out.println("-".repeat(50));1213 double grandTotal→ 0.0 = 0;14 for (String[] item : items) {output================================================== ================================================== --------------------------------------------------name ← Widget A, qty ← 5, price ← 19.99, total ← 99.94999999999999
pass 1 of 313double grandTotal = 0;14for (String[] item : items) {15 String name→ Widget A = item[0]Widget A;16 int qty→ 5 = Integer.parseInt(item[1]5);17 double price→ 19.99 = Double.parseDouble(item[2]19.99);18 double total→ 99.94999999999999 = qty5 * price19.99;19 grandTotal→ 99.94999999999999 += total99.94999999999999;2021 System.out.printf("%-20s %8d $%9.2f $%11.2f%n",22 nameWidget A, qty5, price19.99, total99.94999999999999);23}All 3 passes — pass 1 is the card above pass item[0]item[1]item[2]nameqtypricetotalgrandTotal1 Widget A 5 19.99 Widget A 5 19.99 99.94999999999999 0.0 → 99.94999999999999 2 Widget B 3 29.99 Widget B 3 29.99 89.97 99.94999999999999 → 189.92 3 Widget C 10 9.99 Widget C 10 9.99 99.9 189.92 → 289.82 System.out.printf("%41s $%11.2f%n", "GRAND TOTAL:", grandTotal);
25 System.out.println("-".repeat(50));26 System.out.printf("%41s $%11.2f%n", "GRAND TOTAL:", grandTotal289.82);27 System.out.println("=".repeat(50));28}output-------------------------------------------------- ==================================================printInvoice(customer, items);
60String customer = "John Doe"; //@customer="John Doe", "Ada Lovelace"61printInvoice(customerJohn Doe, items);6263// Progress bars64System.out.println("\n\nProgress Demo:");65printProgress("Downloading", 0);66printProgress("Downloading", 50);output Progress Demo:barWidth ← 30, filled ← 0, bar ← ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
pass 1 of 330public static void printProgress(String taskDownloading, int percent0) {31 int barWidth→ 30 = 30;32 int filled→ 0 = (int) (barWidth30 * percent0 / 100.0);33 String bar→ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ = "█".repeat(filled0) + "░".repeat(barWidth30 - filled);34 System.out.printf("\r%-20s [%s] %3d%%", taskDownloading, bar░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░, percent0);35}All 3 passes — pass 1 is the card above pass percentbarWidthfilledbar1 0 30 0 ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 2 50 30 15 ███████████████░░░░░░░░░░░░░░░ 3 100 30 30 ██████████████████████████████ printProgress("Downloading", 0);
64System.out.println("\n\nProgress Demo:");65printProgress("Downloading", 0);66printProgress("Downloading", 50);67printProgress("Downloading", 100);printProgress("Downloading", 50);
65printProgress("Downloading", 0);66printProgress("Downloading", 50);67printProgress("Downloading", 100);68System.out.println();printProgress("Downloading", 100);
66printProgress("Downloading", 50);67printProgress("Downloading", 100);68System.out.println();6970// Logs71System.out.println("\nLog Entries:");72log("INFO", "Application started");73log("WARNING", "Low memory");output Log Entries:timestamp ← 1706500800000, formatted ← [1706500800000] INFO : Application started
pass 1 of 337public static void log(String levelINFO, String messageApplication started) {38 long timestamp→ 1706500800000 = 1706500800000L;39 String formatted→ [1706500800000] INFO : Application started = String.format("[%d] %-7s: %s",40 timestamp1706500800000, levelINFO, messageApplication started);41 System.out.println(formatted[1706500800000] INFO : Application started);42}output[1706500800000] INFO : Application startedAll 3 passes — pass 1 is the card above pass levelmessagetimestampformatted1 INFO Application started 1706500800000 [1706500800000] INFO : Application started 2 WARNING Low memory 1706500800000 [1706500800000] WARNING: Low memory 3 ERROR Connection failed 1706500800000 [1706500800000] ERROR : Connection failed log("INFO", "Application started");
71System.out.println("\nLog Entries:");72log("INFO", "Application started");73log("WARNING", "Low memory");74log("ERROR", "Connection failed");log("WARNING", "Low memory");
72log("INFO", "Application started");73log("WARNING", "Low memory");74log("ERROR", "Connection failed");String[] statLabels = {"Mean", "Median", "Std Dev", "Min", "Max"};
73 log("WARNING", "Low memory");74 log("ERROR", "Connection failed");7576 // Statistics77 String[] statLabels = {"Mean", "Median", "Std Dev", "Min", "Max"};78 double[] statValues = {75.5, 72.0, 12.3, 45.0, 98.0};79 printStatistics(statLabels, statValues);80}public static void printStatistics(String[] labels, double[] values)
44public static void printStatistics(String[] labels, double[] values) {45 System.out.println("\nStatistics:");46 System.out.println("-".repeat(30));output Statistics: ------------------------------for (int i = 0; i < labels.length; i++)
pass 1 of 548for (int i0 = 0; i < labels.length5; i++) {49 System.out.printf("%-15s: %12.2f%n", labels[i]Mean, values[i]75.5);50}All 5 passes — pass 1 is the card above pass ilabels[i]values[i]1 0 Mean 75.5 2 1 Median 72.0 3 2 Std Dev 12.3 4 3 Min 45.0 5 4 Max 98.0 printStatistics(statLabels, statValues);
78 double[] statValues = {75.5, 72.0, 12.3, 45.0, 98.0};79 printStatistics(statLabels, statValues);80}
customer ← Ada Lovelace
53public static void main(String[] args) {54 // Invoice55 String[][] items = {56 {"Widget A", "5", "19.99"},57 {"Widget B", "3", "29.99"},58 {"Widget C", "10", "9.99"}59 };60 String customer→ Ada Lovelace = "Ada Lovelace";61 printInvoice(customerAda Lovelace, items);grandTotal ← 0.0
5public static void printInvoice(String customerAda Lovelace, String[][] items) {6 System.out.println("=".repeat(50));7 System.out.printf("INVOICE FOR: %s%n", customerAda Lovelace);8 System.out.println("=".repeat(50));9 System.out.printf("%-20s %8s %10s %12s%n", 10 "Item", "Qty", "Price", "Total");11 System.out.println("-".repeat(50));1213 double grandTotal→ 0.0 = 0;14 for (String[] item : items) {output================================================== ================================================== --------------------------------------------------name ← Widget A, qty ← 5, price ← 19.99, total ← 99.94999999999999
pass 1 of 313double grandTotal = 0;14for (String[] item : items) {15 String name→ Widget A = item[0]Widget A;16 int qty→ 5 = Integer.parseInt(item[1]5);17 double price→ 19.99 = Double.parseDouble(item[2]19.99);18 double total→ 99.94999999999999 = qty5 * price19.99;19 grandTotal→ 99.94999999999999 += total99.94999999999999;2021 System.out.printf("%-20s %8d $%9.2f $%11.2f%n",22 nameWidget A, qty5, price19.99, total99.94999999999999);23}All 3 passes — pass 1 is the card above pass item[0]item[1]item[2]nameqtypricetotalgrandTotal1 Widget A 5 19.99 Widget A 5 19.99 99.94999999999999 0.0 → 99.94999999999999 2 Widget B 3 29.99 Widget B 3 29.99 89.97 99.94999999999999 → 189.92 3 Widget C 10 9.99 Widget C 10 9.99 99.9 189.92 → 289.82 System.out.printf("%41s $%11.2f%n", "GRAND TOTAL:", grandTotal);
25 System.out.println("-".repeat(50));26 System.out.printf("%41s $%11.2f%n", "GRAND TOTAL:", grandTotal289.82);27 System.out.println("=".repeat(50));28}output-------------------------------------------------- ==================================================printInvoice(customer, items);
60String customer = "Ada Lovelace";61printInvoice(customerAda Lovelace, items);6263// Progress bars64System.out.println("\n\nProgress Demo:");65printProgress("Downloading", 0);66printProgress("Downloading", 50);output Progress Demo:barWidth ← 30, filled ← 0, bar ← ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
pass 1 of 330public static void printProgress(String taskDownloading, int percent0) {31 int barWidth→ 30 = 30;32 int filled→ 0 = (int) (barWidth30 * percent0 / 100.0);33 String bar→ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ = "█".repeat(filled0) + "░".repeat(barWidth30 - filled);34 System.out.printf("\r%-20s [%s] %3d%%", taskDownloading, bar░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░, percent0);35}All 3 passes — pass 1 is the card above pass percentbarWidthfilledbar1 0 30 0 ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 2 50 30 15 ███████████████░░░░░░░░░░░░░░░ 3 100 30 30 ██████████████████████████████ printProgress("Downloading", 0);
64System.out.println("\n\nProgress Demo:");65printProgress("Downloading", 0);66printProgress("Downloading", 50);67printProgress("Downloading", 100);printProgress("Downloading", 50);
65printProgress("Downloading", 0);66printProgress("Downloading", 50);67printProgress("Downloading", 100);68System.out.println();printProgress("Downloading", 100);
66printProgress("Downloading", 50);67printProgress("Downloading", 100);68System.out.println();6970// Logs71System.out.println("\nLog Entries:");72log("INFO", "Application started");73log("WARNING", "Low memory");output Log Entries:timestamp ← 1706500800000, formatted ← [1706500800000] INFO : Application started
pass 1 of 337public static void log(String levelINFO, String messageApplication started) {38 long timestamp→ 1706500800000 = 1706500800000L;39 String formatted→ [1706500800000] INFO : Application started = String.format("[%d] %-7s: %s",40 timestamp1706500800000, levelINFO, messageApplication started);41 System.out.println(formatted[1706500800000] INFO : Application started);42}output[1706500800000] INFO : Application startedAll 3 passes — pass 1 is the card above pass levelmessagetimestampformatted1 INFO Application started 1706500800000 [1706500800000] INFO : Application started 2 WARNING Low memory 1706500800000 [1706500800000] WARNING: Low memory 3 ERROR Connection failed 1706500800000 [1706500800000] ERROR : Connection failed log("INFO", "Application started");
71System.out.println("\nLog Entries:");72log("INFO", "Application started");73log("WARNING", "Low memory");74log("ERROR", "Connection failed");log("WARNING", "Low memory");
72log("INFO", "Application started");73log("WARNING", "Low memory");74log("ERROR", "Connection failed");String[] statLabels = {"Mean", "Median", "Std Dev", "Min", "Max"};
73 log("WARNING", "Low memory");74 log("ERROR", "Connection failed");7576 // Statistics77 String[] statLabels = {"Mean", "Median", "Std Dev", "Min", "Max"};78 double[] statValues = {75.5, 72.0, 12.3, 45.0, 98.0};79 printStatistics(statLabels, statValues);80}public static void printStatistics(String[] labels, double[] values)
44public static void printStatistics(String[] labels, double[] values) {45 System.out.println("\nStatistics:");46 System.out.println("-".repeat(30));output Statistics: ------------------------------for (int i = 0; i < labels.length; i++)
pass 1 of 548for (int i0 = 0; i < labels.length5; i++) {49 System.out.printf("%-15s: %12.2f%n", labels[i]Mean, values[i]75.5);50}All 5 passes — pass 1 is the card above pass ilabels[i]values[i]1 0 Mean 75.5 2 1 Median 72.0 3 2 Std Dev 12.3 4 3 Min 45.0 5 4 Max 98.0 printStatistics(statLabels, statValues);
78 double[] statValues = {75.5, 72.0, 12.3, 45.0, 98.0};79 printStatistics(statLabels, statValues);80}
Exercise: Practical.java
Format a product receipt with aligned columns showing item name, quantity, unit price, and total