Formatting output is crucial for creating readable and professional-looking console applications. Java provides multiple techniques to control how data is displayed.
public class FormattingExample {
public static void main(String[] args) {
// Numeric formatting
System.out.printf("Integer: %d%n", 42);
System.out.printf("Decimal: %.2f%n", 3.14159);
// String formatting
String name = "LabEx";
System.out.printf("Welcome, %10s!%n", name);
}
}
Specifier |
Purpose |
Example |
%d |
Integer |
printf("%d", 100) |
%f |
Floating-point |
printf("%.2f", 3.14) |
%s |
String |
printf("%s", "Hello") |
%n |
New line |
printf("Text%n") |
Alignment and Padding
public class AlignmentExample {
public static void main(String[] args) {
// Right-aligned with width
System.out.printf("%5d%n", 42);
// Left-aligned with width
System.out.printf("%-5d%n", 42);
// Decimal place control
System.out.printf("%.3f%n", 3.14159);
}
}
graph TD
A[Input Data] --> B[Choose Formatting Method]
B --> C[Apply Format Specifiers]
C --> D[Output Formatted Result]
public class StringFormatExample {
public static void main(String[] args) {
// Creating formatted strings
String formatted = String.format("Name: %s, Age: %d", "John", 25);
System.out.println(formatted);
}
}
Technique |
Use Case |
Flexibility |
printf() |
Console output |
High |
String.format() |
String creation |
High |
Concatenation |
Simple joining |
Low |
public class ComplexFormattingDemo {
public static void main(String[] args) {
// Multiple formatting in one statement
System.out.printf("Name: %10s | Age: %3d | Score: %6.2f%n",
"LabEx User", 25, 92.5);
}
}
Best Practices
- Use appropriate formatting for readability
- Control decimal places for numeric output
- Align text for better presentation
- Choose method based on specific requirements
printf()
is more flexible but slightly slower
- Simple concatenation is faster for basic outputs
- Choose method based on performance needs
By mastering output formatting, you'll create more professional and readable Java applications with LabEx's comprehensive approach to programming.