Clean β’ Professional
In Java, string formatting allows you to create formatted text by embedding variables into strings in a clean and readable way. You can use it to control alignment, width, precision, and data type display.
String.format()String.format() returns a formatted string without printing it directly.printf but gives you a string that can be stored or reused.Syntax
String formattedString = String.format(format, arguments);
format β A format string with placeholders (like %s, %d, %f)arguments β Values to insert into placeholders| Placeholder | Description |
|---|---|
%s | String |
%d | Integer |
%f | Floating-point number |
%c | Character |
%b | Boolean |
%n | Newline |
Example β Basic String Formatting
public class StringFormatExample {
public static void main(String[] args) {
String name = "Alice";
int age = 25;
double salary = 12345.678;
String formatted = String.format("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
System.out.println(formatted);
}
}
Output:
Name: Alice, Age: 25, Salary: 12345.68
Notes:
%.2frounds the floating-point number to 2 decimal places.String.format()does not print the string by itself.
printf()printf() prints a formatted string directly to the console.String.format() but outputs immediately.Syntax
System.out.printf(format, arguments);
Example β Using printf
public class PrintfExample {
public static void main(String[] args) {
String product = "Laptop";
int quantity = 5;
double price = 999.99;
System.out.printf("Product: %s, Quantity: %d, Price: $%.2f%n", product, quantity, price);
}
}
Output:
Product: Laptop, Quantity: 5, Price: $999.99
Notes:
%nadds a new line (platform-independent).printfis often used for console-based reports and tables.
Align Text and Numbers
System.out.printf("|%-10s|%5d|%10.2f|%n", "Item", 12, 345.67);
Output:
|Item | 12| 345.67|
%-10s β Left-align string in 10 spaces%5d β Right-align integer in 5 spaces%10.2f β Right-align float in 10 spaces with 2 decimalsExample β Multiple Lines in a Table
System.out.printf("%-10s %-10s %-10s%n", "Name", "Age", "Salary");
System.out.printf("%-10s %-10d %-10.2f%n", "Alice", 25, 12345.67);
System.out.printf("%-10s %-10d %-10.2f%n", "Bob", 30, 9876.54);
Output:
Name Age Salary
Alice 25 12345.67
Bob 30 9876.54
Notes:
- Perfect for console-based reports and formatted tables.
- Makes output readable and professional.
String.format() β Returns formatted string (store or reuse).printf() β Prints formatted string directly.%s, %d, %f, etc.) to control output.%n instead of \\n for cross-platform newlines.