Format a table with Java printf statements |Video upload date:  · Duration: PT6M43S  · Language: EN

Quick guide to format console tables in Java using printf and format specifiers for aligned columns precision and readable output

If your console output looks like a sloppy grocery list then welcome. This short guide shows how to use Java printf and format specifiers to produce neat, readable tables that humans can scan without therapy. We keep the output aligned, the decimals respectful, and the code reusable.

Plan columns and widths

Start like a civilized person and decide on column labels and character widths. Think about the longest expected name and the largest number of digits you will get. Reserve a little slack so your table does not wrap mid drama.

Simple rules to follow

  • Give numbers a fixed width so decimals line up
  • Give text columns a bit more room and left align them when that makes sense
  • Print the header row with the exact same format string as the data rows

Choose the right format specifiers and flags

Match Java types to specifiers. Use %s for strings, %d for integers and %f for floating point numbers. Add a width to reserve space and add precision to control decimal places. A minus flag before the width left aligns text like %-20s, while a plain width right aligns numbers like %8.2f.

Build a reusable printf template

Make one format string and reuse it. This is the boring magic that keeps every row obedient to the same column rules.

String fmt = "%-15s %8.2f\n"
System.out.printf(fmt, name, price)

Loop rows and apply the template

Run a loop and feed each row into the template. Consistency wins here. One format string prevents one row from trying to steal the spotlight.

for (Product p : products) {
    System.out.printf(fmt, p.getName(), p.getPrice())
}

Tweaks that actually matter

If you want exactly two decimals use %8.2f. If a text column should hug the left edge use %-20s. If numbers should line up add sufficient width and right alignment. These are small changes that make big visual improvements.

Quick checklist

  • Plan column widths before typing anything
  • Pick the right specifiers for each type
  • Assemble one printf template and reuse it
  • Print headers with the same template as data rows
  • Adjust precision and alignment flags until your eyeballs approve

Follow these steps and your console tables will stop resembling modern art. Use width, precision and the minus flag together and you will have tables that are both readable and annoyingly professional. If you need help tuning a specific layout paste a sample and we will make it behave.

I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!

This is a dedicated watch page for a single video.