Stream formatting allows precise control over how data is displayed, enabling developers to create structured and visually appealing output in LabEx programming environments.
// Basic format specifiers
System.out.printf("Integer: %d%n", 100); // Decimal integer
System.out.printf("Float: %f%n", 3.14159); // Floating-point
System.out.printf("String: %s%n", "LabEx"); // String
// Width and precision
System.out.printf("Formatted number: %5.2f%n", 3.14159); // 5 total width, 2 decimal places
System.out.printf("Left-aligned: %-10s%n", "Java"); // Left-aligned with 10 character width
1. Multiple Arguments
String name = "Developer";
int age = 25;
double salary = 5000.50;
System.out.printf("Name: %s, Age: %d, Salary: %.2f%n", name, age, salary);
Specifier |
Description |
Example |
%d |
Decimal integer |
42 |
%f |
Floating-point |
3.14 |
%s |
String |
"Hello" |
%n |
Newline |
Platform-independent |
%x |
Hexadecimal |
2A |
graph LR
A[Raw Data] --> B[Format Specifiers]
B --> C[Formatted Output]
// Combining multiple formatting techniques
System.out.printf("| %-15s | %5d | %8.2f |%n", "Product", 10, 99.99);
String formattedString = String.format("Welcome %s to LabEx!", "Java Developer");
System.out.println(formattedString);
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(3.14159));
printf()
is more flexible but slower
- Direct concatenation is faster for simple outputs
- Use appropriate method based on complexity
Best Practices
- Choose appropriate format specifiers
- Use precision control
- Avoid excessive formatting in performance-critical code
- Consider readability and performance balance
Mastering stream formatting methods provides powerful tools for creating structured and professional output in Java programming.