java.util.Formatter
is a utility class used to format data (like numbers, strings, etc.) into formatted strings. It behaves similarly to C-style printf
formatting and is often used in combination with String.format()
, PrintWriter
, or directly with console output.
Formatter allows precise control over string formatting, such as padding, alignment, decimal precision, and locale-specific formatting.
Commonly Used Constructors and Methods


Common Formatter Specifiers

Simple Program
import java.util.Formatter; public class SimpleFormatterExample { public static void main(String[] args) { Formatter formatter = new Formatter(); formatter.format("Name: %s%nAge: %d%nSalary: %.2f", "Mahesh", 28, 98765.432); System.out.println(formatter.toString()); formatter.close(); } } /* Name: Alice Age: 28 Salary: 98765.43 */
Problem Statement:
LotusJavaPrince and Mahesh are building a Bank Statement Generator. The system should display user transactions in a neatly formatted tabular format using java.util.Formatter
. Each transaction includes Date, Description, and Amount. The table must align properly, use padding, and round amounts to 2 decimal places.
import java.util.Formatter; class Transaction { String date; String description; double amount; public Transaction(String date, String description, double amount) { this.date = date; this.description = description; this.amount = amount; } } public class BankStatementFormatter { public static void main(String[] args) { Transaction[] transactions = { new Transaction("2025-05-01", "Deposit", 10000.00), new Transaction("2025-05-03", "ATM Withdrawal", -1500.50), new Transaction("2025-05-05", "Online Purchase", -230.75), new Transaction("2025-05-10", "Salary Credit", 25000.00) }; Formatter formatter = new Formatter(); formatter.format("%-15s %-25s %10s%n", "Date", "Description", "Amount"); formatter.format("%-15s %-25s %10s%n", "----", "-----------", "------"); for (Transaction t : transactions) { formatter.format("%-15s %-25s %10.2f%n", t.date, t.description, t.amount); } System.out.println(formatter.toString()); formatter.close(); } }
Output
Date Description Amount
---- ----------- ------
2025-05-01 Deposit 10000.00
2025-05-03 ATM Withdrawal -1500.50
2025-05-05 Online Purchase -230.75
2025-05-10 Salary Credit 25000.00
Code language: CSS (css)
java.util.Formatter
provides powerful string formatting similar to printf
.
- Supports various format specifiers for strings, numbers, and dates.
- Use cases include reports, logs, invoices, and console output.
- Can be used directly or with
System.out.printf
,String.format()
, or file writers.