Practical Examples
Real-World Printf Applications
Printf formatting is crucial in various programming scenarios, from data presentation to logging and report generation.
1. Financial Reporting
public class FinancialReport {
public static void printInvoice(String customer, double amount, boolean isPaid) {
System.out.printf("Customer: %-15s | Amount: $%,.2f | Status: %s\n",
customer, amount, isPaid ? "Paid" : "Pending");
}
public static void main(String[] args) {
printInvoice("LabEx Platform", 1250.75, true);
}
}
public class ScientificCalculator {
public static void displayResults(String experiment,
double mean,
double standardDeviation) {
System.out.printf("Experiment: %s\n", experiment);
System.out.printf("Mean Value: %10.4f\n", mean);
System.out.printf("Std Deviation: %10.4f\n", standardDeviation);
}
public static void main(String[] args) {
displayResults("Quantum Simulation", 0.6782, 0.0123);
}
}
3. System Logging
public class SystemLogger {
public static void logEvent(String level, String message, long timestamp) {
System.out.printf("[%5s] %tF %<tT - %s\n",
level, timestamp, message);
}
public static void main(String[] args) {
logEvent("INFO", "Server initialized", System.currentTimeMillis());
}
}
graph TD
A[Printf Formatting] --> B[Basic Formatting]
A --> C[Intermediate Formatting]
A --> D[Advanced Formatting]
B --> E[Simple Type Conversion]
C --> F[Width and Alignment]
D --> G[Complex Precision Control]
Formatting Method |
Complexity |
Performance |
Readability |
Concatenation |
Low |
High |
Medium |
String.format() |
Medium |
Medium |
High |
System.out.printf() |
High |
Low |
Very High |
Error Handling Strategies
public class SafeFormatting {
public static void safeFormat(String data) {
try {
System.out.printf("Processed Data: %s\n",
data != null ? data : "N/A");
} catch (IllegalFormatException e) {
System.err.println("Formatting error: " + e.getMessage());
}
}
}
Best Practices
- Use printf for complex formatting
- Validate input before formatting
- Consider performance in high-frequency operations
- Leverage LabEx platform's debugging tools for format testing
Internationalization Considerations
import java.util.Locale;
public class InternationalFormatter {
public static void displayCurrency(double amount, Locale locale) {
System.out.printf(locale, "Amount: %,.2f\n", amount);
}
}