String formatting is crucial for creating readable and structured text output. Java offers multiple approaches to format strings efficiently.
The String.format()
method provides powerful string formatting capabilities:
public class StringFormattingDemo {
public static void main(String[] args) {
// Basic formatting
String name = "LabEx";
int version = 2023;
String formattedString = String.format("Welcome to %s version %d", name, version);
System.out.println(formattedString);
}
}
Specifier |
Description |
Example |
%s |
String |
"Hello" |
%d |
Integer |
42 |
%f |
Floating-point |
3.14 |
%.2f |
Float with 2 decimal places |
3.14 |
%n |
New line |
- |
public class AdvancedFormattingDemo {
public static void main(String[] args) {
// Numeric formatting
double price = 99.99;
System.out.printf("Product price: $%.2f%n", price);
// Alignment and padding
System.out.printf("%-10s | %5d%n", "Quantity", 250);
}
}
graph LR
A[Raw Data] --> B[Formatting Specifiers]
B --> C[Formatted String]
C --> D[Output]
Printf Method
The printf()
method offers inline formatting:
public class PrintfDemo {
public static void main(String[] args) {
String product = "Java Tutorial";
int users = 1000;
System.out.printf("Product: %s, Users: %d%n", product, users);
}
}
Best Practices
- Choose appropriate formatting specifiers
- Use
String.format()
for complex string creation
- Utilize
printf()
for direct console output
- Consider performance for large-scale formatting
Mastering string formatting in Java enables you to create more readable and professional output in your applications.