Practical Examples
1. Financial Reporting
public class FinancialReporting {
public static void main(String[] args) {
double[] expenses = {1234.56, 987.65, 2345.67};
System.out.println("Monthly Expense Report:");
for (double expense : expenses) {
System.out.printf("Expense: $%,.2f%n", expense);
}
double total = Arrays.stream(expenses).sum();
System.out.printf("Total Expenses: $%,.2f%n", total);
}
}
public class ScientificDataFormatter {
public static void main(String[] args) {
double[] measurements = {0.00034, 1.2345, 567.89};
System.out.println("Scientific Notation:");
for (double value : measurements) {
System.out.printf("Value: %e%n", value);
}
}
}
graph TD
A[Formatting Complexity] --> B[Basic Formatting]
A --> C[Intermediate Formatting]
A --> D[Advanced Formatting]
B --> B1[Simple Type Conversion]
B --> B2[Basic Alignment]
C --> C1[Precision Control]
C --> C2[Width Specification]
D --> D1[Complex Numeric Formatting]
D --> D2[Internationalization]
public class UserProfileFormatter {
public static void main(String[] args) {
String[] users = {
"Alice Johnson",
"Bob Smith",
"Charlie Brown"
};
int[] ages = {28, 35, 42};
double[] salaries = {45000.50, 67500.75, 82300.25};
System.out.printf("%-15s | %5s | %10s%n",
"Name", "Age", "Salary");
System.out.println("-".repeat(40));
for (int i = 0; i < users.length; i++) {
System.out.printf("%-15s | %5d | $%,10.2f%n",
users[i], ages[i], salaries[i]);
}
}
}
Technique |
Use Case |
Complexity |
Performance |
Basic Printf |
Simple output |
Low |
High |
Precision Formatting |
Financial/Scientific |
Medium |
Medium |
Complex Formatting |
Detailed Reports |
High |
Low |
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatter {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.printf("Current Date and Time:%n");
System.out.printf("%tF %tT%n", now, now);
// Customized formatting
System.out.printf("Custom Format: %td/%tm/%tY%n",
now, now, now);
}
}
Best Practices for Printf
- Choose appropriate format specifiers
- Use precision wisely
- Consider readability
- Be mindful of performance in loops
- Leverage LabEx learning resources for advanced techniques