Skip to Content
Course content

277: Formatting Text with String.format and Formatter

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 the Formatter class. It's basically the engine that powers String.format(), but you can point it directly at an output stream, like System.out, without creating those intermediate strings.

I swapped my loop to use a Formatter instance 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 %n at the end. I used \n before, but %n is 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. Using Formatter directly 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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.