Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
277: Formatting Text with String.format and Formatter
I was working on a small internal tool yesterday to generate transaction reports for a client, and I hit a wall that I think we've all hit: the "concatenation nightmare." I started by just using the + operator to glue together strings, dates, and amounts. It looked something like this:
System.out.println("Date: " + date + " | Description: " + desc + " | Amount: $" + amount);
It works, sure. But the second I tried to print a list of these, it looked like a jagged mess because "Coffee" is shorter than "Monthly Rent Payment." The columns didn't line up, and the doubles were printing out as 12.500000000001. It looked amateur. I decided to scrap the concatenation and see if I could get String.format() to do the heavy lifting.
Taming the Decimal Chaos
My first instinct was to just use a basic placeholder. I tried %s for the description and %f for the amount. Here is what happened:
String line = String.format("%s %f", "Coffee", 4.50);
// Result: "Coffee 4.500000"
Better, but those trailing zeros are annoying. I remember seeing something about "precision" in the docs. I tried adding a .2 between the percent sign and the f. This tells Java, "I only want two digits after the decimal point."
String line = String.format("%s %.2f", "Coffee", 4.50);
// Result: "Coffee 4.50"
Now we're talking. It actually looks like currency now.
Forcing the Columns to Align
The decimals are solved, but my columns are still shifting. If I have "Coffee" and "Rent," the amount for "Coffee" starts way earlier than the amount for "Rent." I need a fixed width. I tried putting a number before the s to see what happens.
String line1 = String.format("%15s %.2f", "Coffee", 4.50);
String line2 = String.format("%15s %.2f", "Monthly Rent", 1200.00);
/*
Result:
Coffee 4.50
Monthly Rent 1200.00
*/
That 15 told Java to make the string exactly 15 characters wide, right-aligned. If the text is shorter, it pads the left side with spaces. If I wanted it left-aligned—which usually looks better for descriptions—I just add a minus sign: %-15s. Let's see that in action:
String line1 = String.format("%-15s %.2f", "Coffee", 4.50); String line2 = String.format("%-15s %.2f", "Monthly Rent", 1200.00); /* Result: Coffee 4.50 Monthly Rent 1200.00 */Suddenly, it looks like a professional ledger. The
-flag is a lifesaver for creating tables in the console.Moving Beyond String Objects
While
String.format()is great for small things, I realized I was creating a brand new String object for every single line of my 500-page report. That's a lot of garbage for the GC to clean up. I started looking into theFormatterclass. It's basically the engine that powersString.format(), but you can point it directly at an output stream, likeSystem.out, without creating those intermediate strings.I swapped my loop to use a
Formatterinstance like this:import java.util.Formatter; Formatter formatter = new Formatter(System.out, "UTF-8"); formatter.format("%-15s %.2f%n", "Coffee", 4.50); formatter.format("%-15s %.2f%n", "Monthly Rent", 1200.00); formatter.close();Note the
%nat the end. I used\nbefore, but%nis the platform-independent newline character. It's a small detail, but it keeps the code from breaking if the report is generated on Windows vs. Linux. UsingFormatterdirectly is cleaner and more efficient when you're streaming a lot of formatted data to a file or the console.
📋 Practical Task
Building a Formatted Inventory Ledger
You are tasked with creating a simple inventory display for a warehouse. You have three items with different name lengths and prices. Instead of using concatenation, use String.format() or a Formatter to create a clean, tabular output.
Requirements:
- The item name must be left-aligned in a column 20 characters wide.
- The quantity must be right-aligned in a column 10 characters wide.
- The price must be right-aligned in a column 10 characters wide, formatted to exactly 2 decimal places.
- Each item must be on a new line.
Example Target Output:
Item Name Qty Price
Wireless Mouse 15 25.99
Mechanical Keyboard 5 120.00
USB-C Cable 50 8.50
Create a Java class that prints this ledger to the console using the formatting techniques discussed in the lesson.
There are no comments for now.