String.format() Method in Java creates formatted strings by inserting values into placeholders and controlling how text, numbers, dates, and other data appear. It is particularly useful when applications need readable messages, reports, tables, prices, percentages, dates, or dynamically generated output.
Instead of joining multiple values with repeated + operators, developers can create a format pattern and supply the required arguments. This approach produces cleaner, more consistent, and easier-to-maintain Java code.
What Is the String.format() Method in Java?
String.format() is a static method of Java’s String class. It accepts a format string and one or more arguments, applies the requested formatting rules, and returns a new string.
The original values are not modified. The method simply creates a formatted representation of them.
Consider this basic example:
String name = "Daniel";
int age = 28;
String message = String.format(
"My name is %s and I am %d years old.",
name,
age
);
System.out.println(message);
Output:
My name is Daniel and I am 28 years old.
In this example:
%srepresents a string.%drepresents a decimal integer.namereplaces%s.agereplaces%d.
String.format() Method Syntax
Java provides two commonly used versions of the method.
Default Locale Syntax
String.format(String format, Object... args)
This version uses the system’s default locale.
Read More: Java Records in Java 16: Syntax, Features, and Examples
Custom Locale Syntax
String.format(Locale locale, String format, Object... args)
This version lets developers control language-sensitive formatting for numbers and other values.
Example:
String result = String.format(
Locale.US,
"Price: $%,.2f",
12500.75
);
System.out.println(result);
Output:
Price: $12,500.75
Parameters and Return Value
The String.format() method uses the following parameters:
format: The string containing normal text and format specifiers.args: The values inserted into the format specifiers.locale: An optional locale that controls regional formatting conventions.
The method returns a new formatted String.
String product = "Keyboard";
double price = 49.99;
String details = String.format(
"Product: %s | Price: $%.2f",
product,
price
);
The variable details stores:
Product: Keyboard | Price: $49.99

Understanding Java Format Specifiers
A format specifier tells Java how an argument should be displayed. It begins with a percent sign and normally ends with a conversion character.
Its general structure is:
%[argument_index$][flags][width][.precision]conversion
Not every section is required. A simple format specifier may contain only % and a conversion character.
For example:
String.format("%s", "Java");
Here, %s instructs Java to represent the argument as a string.
Common String.format() Specifiers
| Specifier | Purpose | Example value |
|---|---|---|
%s | String or general object | "Java" |
%d | Decimal integer | 150 |
%f | Floating-point number | 19.95 |
%b | Boolean value | true |
%c | Character | 'A' |
%x | Hexadecimal integer | 255 |
%o | Octal integer | 64 |
%e | Scientific notation | 1250.5 |
%h | Hash code | An object |
%n | Platform-specific line break | No argument |
%% | Literal percent sign | No argument |
Formatting Strings With %s
The %s specifier converts an argument into its string representation.
String language = "Java";
String result = String.format(
"Programming language: %s",
language
);
System.out.println(result);
Output:
Programming language: Java
Objects can also be supplied to %s. Java typically uses the object’s toString() method to produce the formatted value.
String result = String.format(
"Current user: %s",
user
);
Converting Text to Uppercase
Using %S instead of %s converts the formatted text to uppercase.
String result = String.format(
"Language: %S",
"Java"
);
System.out.println(result);
Output:
Language: JAVA
Formatting Integers With %d
The %d specifier formats whole numbers in decimal form.
int quantity = 25;
String result = String.format(
"Available quantity: %d",
quantity
);
System.out.println(result);
Output:
Available quantity: 25
Adding Thousands Separators
The comma flag adds grouping separators according to the selected locale.
int population = 1500000;
String result = String.format(
"%,d",
population
);
System.out.println(result);
With a US-style locale, the output is:
1,500,000
Adding Leading Zeros
A number can be padded with leading zeros by specifying a width and using the 0 flag.
int orderNumber = 42;
String result = String.format(
"%06d",
orderNumber
);
System.out.println(result);
Output:
000042
The complete formatted value occupies six character positions.
Formatting Decimal Numbers With %f
The %f specifier formats floating-point values.
double value = 45.6789;
String result = String.format(
"%f",
value
);
System.out.println(result);
Output:
45.678900
By default, %f displays six digits after the decimal point.
Controlling Decimal Places
Precision can be defined after a period.
double price = 45.6789;
String result = String.format(
"%.2f",
price
);
System.out.println(result);
Output:
45.68
Java rounds the number to two decimal places.
Formatting Currency Values
double price = 1299.5;
String result = String.format(
Locale.US,
"Total: $%,.2f",
price
);
System.out.println(result);
Output:
Total: $1,299.50
This pattern includes a thousands separator and always displays two decimal places.
Formatting Percentages
A percentage can be created by multiplying a decimal value by 100 and adding a literal percent sign with %%.
double completionRate = 0.875;
String result = String.format(
"Progress: %.1f%%",
completionRate * 100
);
System.out.println(result);
Output:
Progress: 87.5%
The %% sequence displays one percent sign and does not require an argument.
Formatting Boolean Values
The %b specifier creates a Boolean representation.
boolean active = true;
String result = String.format(
"Account active: %b",
active
);
System.out.println(result);
Output:
Account active: true
When %b receives a non-null object, it normally produces true. A null value produces false.
Formatting Characters
The %c specifier formats a character or a valid Unicode code point.
char grade = 'A';
String result = String.format(
"Final grade: %c",
grade
);
System.out.println(result);
Output:
Final grade: A
Using uppercase %C converts applicable letters to uppercase.
Formatting Hexadecimal and Octal Numbers
Java can represent integers in hexadecimal and octal formats.
Hexadecimal Example
int number = 255;
String result = String.format(
"Hexadecimal: %x",
number
);
System.out.println(result);
Output:
Hexadecimal: ff
Use %X to display uppercase hexadecimal letters.
String result = String.format("%X", 255);
Output:
FF
Octal Example
String result = String.format(
"Octal: %o",
64
);
System.out.println(result);
Output:
Octal: 100
Formatting Scientific Notation
The %e specifier formats floating-point values using scientific notation.
double distance = 1250000.0;
String result = String.format(
"%.2e",
distance
);
System.out.println(result);
Output:
1.25e+06
Use %E when an uppercase E is preferred.
Setting Minimum Field Width
A width value defines the minimum number of character positions used for the output.
String result = String.format(
"|%10s|",
"Java"
);
System.out.println(result);
Output:
| Java|
The value is right-aligned by default and padded with spaces on the left.
Left-Aligning a Value
Use the - flag to align a value to the left.
String result = String.format(
"|%-10s|",
"Java"
);
System.out.println(result);
Output:
|Java |
This formatting is useful when creating console tables or aligned reports.
Combining Width and Precision
Width and precision can be used together.
double amount = 123.4567;
String result = String.format(
"|%10.2f|",
amount
);
System.out.println(result);
Output:
| 123.46|
In %10.2f:
10is the minimum field width..2limits the output to two digits after the decimal point.fformats the value as a decimal number.
Reusing and Reordering Arguments
Java allows format specifiers to refer to arguments by position. The argument index starts at 1.
String result = String.format(
"%2$s scored %1$d points.",
95,
"Maria"
);
System.out.println(result);
Output:
Maria scored 95 points.
In this example:
%1$drefers to the first argument.%2$srefers to the second argument.
Reusing the Previous Argument
The < flag reuses the argument used by the previous format specifier.
String result = String.format(
"%s scored %<s again.",
"Alex"
);
System.out.println(result);
Output:
Alex scored Alex again.
Indexed arguments are often clearer when a format string uses the same value multiple times.
Formatting Dates and Times
String.format() supports date and time conversion characters. Date and time specifiers use %t or %T followed by another conversion character.
LocalDate date = LocalDate.of(2026, 9, 12);
String result = String.format(
"Date: %tF",
date
);
System.out.println(result);
Output:
Date: 2026-09-12
Common date and time conversions include:
| Specifier | Meaning |
|---|---|
%tF | Date in year-month-day format |
%tY | Four-digit year |
%tm | Two-digit month |
%td | Two-digit day |
%tH | Hour in 24-hour format |
%tM | Minute |
%tS | Second |
%tB | Full month name |
%tA | Full weekday name |
Example:
LocalDate date = LocalDate.of(2026, 9, 12);
String result = String.format(
Locale.US,
"%tA, %tB %td, %tY",
date,
date,
date,
date
);
System.out.println(result);
Output:
Saturday, September 12, 2026
For modern applications with complex date patterns, the java.time package and DateTimeFormatter may provide clearer and more specialized formatting.
Using Locale With String.format()
A locale controls regional formatting conventions, including decimal separators and digit grouping.
double amount = 12345.67;
String usValue = String.format(
Locale.US,
"%,.2f",
amount
);
String germanValue = String.format(
Locale.GERMANY,
"%,.2f",
amount
);
System.out.println(usValue);
System.out.println(germanValue);
Typical output:
12,345.67
12.345,67
Using an explicit locale creates predictable output and is especially important for international applications.
Creating Aligned Console Tables
String.format() is useful for creating structured command-line output.
String header = String.format(
"%-15s %10s %10s",
"Product",
"Quantity",
"Price"
);
String row = String.format(
"%-15s %10d %10.2f",
"Keyboard",
5,
49.99
);
System.out.println(header);
System.out.println(row);
Output:
Product Quantity Price
Keyboard 5 49.99
The width and alignment settings keep each value in the correct column.
String.format() vs String Concatenation
String concatenation uses the + operator:
String message =
"User " + name + " has " + points + " points.";
The same statement with String.format() is:
String message = String.format(
"User %s has %d points.",
name,
points
);
String.format() is often clearer when a message contains several dynamic values or needs alignment, rounding, padding, or locale-specific formatting.
Simple concatenation may still be appropriate for short expressions that do not require special formatting.
String.format() vs formatted()
Modern Java versions also allow the formatted() instance method on a format string.
String message = "User %s has %d points."
.formatted("Aisha", 150);
This produces the same result as:
String message = String.format(
"User %s has %d points.",
"Aisha",
150
);
formatted() can be more readable when the format pattern is the main part of the expression. String.format() remains useful when an explicit locale is required or when a project follows the traditional static method style.
String.format() vs printf()
Both methods use similar formatting rules, but their results are handled differently.
String.format() returns a formatted string:
String result = String.format(
"Score: %d",
90
);
System.out.printf() writes formatted output directly to the console:
System.out.printf(
"Score: %d%n",
90
);
Use String.format() when the result needs to be stored, returned, logged, or passed to another method. Use printf() when the output only needs to be displayed.
Common String.format() Exceptions
Incorrect format patterns or incompatible argument types can cause runtime exceptions.
IllegalFormatConversionException
This exception occurs when a format specifier does not support the supplied argument type.
String result = String.format(
"%d",
"Java"
);
The %d specifier expects an integer-compatible value, but it receives a string.
MissingFormatArgumentException
This occurs when a format specifier does not have a corresponding argument.
String result = String.format(
"%s is %d years old.",
"David"
);
The format expects two arguments, but only one is supplied.
UnknownFormatConversionException
This exception may occur when the format string contains an unsupported conversion.
String result = String.format(
"%q",
"Java"
);
Java does not recognize %q as a valid conversion.
Best Practices for Using String.format()
Follow these practices to produce clear and reliable formatted strings:
- Match every format specifier with a compatible argument type.
- Use meaningful and readable format patterns.
- Specify precision when displaying currency or measurements.
- Use an explicit locale when output must remain regionally consistent.
- Prefer
%nover\nfor platform-independent line breaks. - Avoid overly complex format strings that are difficult to maintain.
- Test width and alignment when creating tables.
- Do not use formatting alone for currency calculations.
- Keep translatable user messages separate when building multilingual software.
- Consider
DateTimeFormatterfor complex date and time patterns.
Frequently Asked Questions
What is String.format() in Java?
String.format() is a static method that inserts supplied values into a format pattern and returns a new formatted string. It can format text, integers, decimal numbers, dates, times, Boolean values, and other objects.
Does String.format() print the result?
No. String.format() returns a string but does not print it automatically.
String result = String.format(
"Total: %.2f",
99.95
);
System.out.println(result);
The formatted value must be printed explicitly when console output is required.
What does %s mean in String.format()?
The %s specifier displays an argument as a string. If the argument is an object, Java generally uses its toString() representation.
What does %d mean in Java formatting?
The %d specifier formats an integer in decimal notation. It is suitable for values such as byte, short, int, long, and their corresponding wrapper types.
How can I limit a number to two decimal places?
Use %.2f:
double number = 15.678;
String result = String.format(
"%.2f",
number
);
The result is:
15.68
How do I add leading zeros in Java?
Use the 0 flag followed by the required width.
String result = String.format(
"%05d",
42
);
Output:
00042
How do I include a percent sign in String.format()?
Use two percent signs:
String result = String.format(
"Success rate: %.1f%%",
98.5
);
Output:
Success rate: 98.5%
Can String.format() format dates?
Yes. Date and time specifiers begin with %t or %T. For example, %tF produces a date in year-month-day format. For advanced date handling, DateTimeFormatter is usually more flexible.
What is the difference between String.format() and printf()?
String.format() returns the formatted text as a string, while printf() sends formatted text directly to an output stream such as the console. Both use similar format specifiers.
Does String.format() change the original string?
No. Java strings are immutable. The method creates and returns a new string without modifying the original format pattern or supplied values.
Is String.format() suitable for currency?
It can format a numeric value to look like currency, but NumberFormat.getCurrencyInstance() is generally better when an application needs locale-aware currency symbols and conventions. Monetary calculations should also use an appropriate numeric type such as BigDecimal.
Can null be used with String.format()?
Yes, but the result depends on the conversion. For example, %s commonly formats a null reference as null, while %b produces false.
Conclusion
The String.format() Method in Java offers a structured way to create readable and consistent text. It can insert dynamic values, control decimal precision, align columns, add padding, format dates, and apply regional number conventions.
