The format() method builds a new String from a template with placeholders like %s and %d. It is static, printf-style, and ideal for readable output that mixes text, numbers, and fixed decimal places.
01
Template String
Placeholders + text.
02
Static Method
String.format().
03
%s %d %f
Common specifiers.
04
Precision
%.2f decimals.
05
Varargs
Many arguments.
06
vs printf
Return vs print.
Fundamentals
Definition and Usage
In Java, String.format(String format, Object... args) is a static method on java.lang.String. You provide a format string containing specifiers such as %s, plus values that replace each specifier in order. The method returns the completed string.
The syntax is inspired by C's printf. Use it for user-facing messages, invoices, progress logs, and anywhere a template reads clearer than chaining many + operators.
💡
Beginner Tip
Count your placeholders and match them to arguments in the same order. String.format(" %d %s", 3, "apples") puts the integer first, then the string.
Foundation
📝 Syntax
The format() method has several overloads. The most common form is:
java
public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)
Parameters
format — the template string with format specifiers (for example %s, %d, %.2f).
args — zero or more values inserted into the template in order.
l — (optional overload) a Locale for locale-sensitive formatting of numbers and dates.
Return Value
Returns a new formatted String.
Exceptions
Throws IllegalFormatException if the format string is invalid or an argument type does not match its specifier.
Cheat Sheet
⚡ Quick Reference
Specifier
Used for
Example
%s
String / general text
String.format("Hi, %s", "Java")
%d
Integer (decimal)
String.format("Count: %d", 42)
%f
Floating-point
String.format("Pi: %.2f", 3.14159)
%n
Platform line break
String.format("Line 1%nLine 2")
%%
Literal percent sign
String.format("Done: 100%%")
Greeting
String.format("Hello, %s!", name)
Insert a name
Money
String.format("$%.2f", price)
Two decimal places
Multiple
String.format("%d %s", qty, item)
Int then string
Print
System.out.printf("%s%n", msg)
Print, not return
Hands-On
Examples Gallery
These programs run in Java 8+. They show string insertion, decimal formatting, multiple arguments, zero-padding, and comparison with printf.
📚 Getting Started
Insert a string value into a template with %s.
Example 1 — Basic String Formatting
Replace %s with the argument "Java".
java
public class StringFormatExample {
public static void main(String[] args) {
String formatted = String.format("Hello, %s!", "Java");
System.out.println(formatted);
}
}
📤 Output:
Hello, Java!
How It Works
%s is a general-purpose placeholder. Java converts the argument to text and inserts it at that position in the template.
Example 2 — Formatting Decimal Numbers
Use %.2f to show exactly two digits after the decimal point.
java
public class PriceFormat {
public static void main(String[] args) {
double price = 49.99;
String message = String.format("The price is $%.2f", price);
System.out.println(message);
}
}
📤 Output:
The price is $49.99
How It Works
The .2 between % and f sets precision. Without it, %f might print many decimal places by default.
📈 Practical Patterns
Multiple placeholders, padding, and printing formatted text.
Example 3 — Multiple Arguments
Match each specifier to an argument in order: %d for count, %s for item name.
java
public class MultipleArgs {
public static void main(String[] args) {
int quantity = 3;
String item = "Apples";
String order = String.format("I want %d %s", quantity, item);
System.out.println(order);
}
}
📤 Output:
I want 3 Apples
How It Works
The first specifier consumes the first argument after the format string, the second specifier the next, and so on.
Example 4 — Zero-Padded Numbers
%05d pads an integer to five digits with leading zeros—useful for IDs and counters.
java
public class PaddedId {
public static void main(String[] args) {
int ticket = 42;
String id = String.format("Ticket #%05d", ticket);
System.out.println(id);
}
}
📤 Output:
Ticket #00042
How It Works
The 5 sets minimum width; the leading 0 fills empty spaces with zeros instead of spaces.
Example 5 — format() vs printf()
String.format returns a string; System.out.printf prints directly.
java
public class FormatVsPrintf {
public static void main(String[] args) {
String name = "Mari";
String stored = String.format("Welcome, %s!", name);
System.out.println("Stored: " + stored);
System.out.print("Printed: ");
System.out.printf("Welcome, %s!", name);
System.out.println();
}
}
📤 Output:
Stored: Welcome, Mari!
Printed: Welcome, Mari!
How It Works
Both use the same formatting rules. Choose format() when you need the result as a variable; choose printf for immediate console output.
Applications
🚀 Common Use Cases
User messages — build personalized greetings and status lines from variables.
Financial display — show currency with fixed decimal places using %.2f.
Logging — create consistent log lines with timestamps, levels, and details.
Reports and tables — align columns with width and padding specifiers.
Test expected output — compose predictable strings for assertions.
🧠 How format() Works
1
You pass a template
The format string contains literal text and %specifiers.
Input
2
Specifiers are validated
Invalid syntax or mismatched types throw IllegalFormatException.
Validate
3
Arguments are inserted
Each value replaces the next specifier, formatted per its type and flags.
Format
=
📄
New String returned
The finished text is ready to print, return, or store.
Important
📝 Notes
format() is static—call String.format(...), not myString.format(...).
Specifiers and argument types must match: use %d for integers, %f for floating-point, %s for general objects.
Use %% to output a literal percent sign in the template.
For locale-specific number formatting, use the overload with Locale.
In loops, building one formatted string per iteration is fine; avoid unnecessary repeated formatting of unchanged templates.
Performance
⚡ Optimization
String.format() is efficient for typical use but allocates a new string each call. In tight loops logging thousands of lines, consider whether a simpler append or a dedicated logging API fits better. For most application code, readability wins—prefer format() over long + chains when placeholders and precision matter.
Wrap Up
Conclusion
The format() method is a versatile way to compose strings from templates. Placeholders keep mixed text and numbers readable, and precision flags control how values appear.
Remember it is static, match specifiers to argument types, and use printf when you only need console output. With those basics, formatted strings become easy to write and maintain in real programs.
Use String.format() for templates with mixed types
Pick the right specifier: %s, %d, %f
Use %.2f (or similar) for consistent decimal display
Keep placeholder order aligned with argument order
Store the result when you need the string more than once
❌ Don’t
Call format() on a string instance
Pass a String to %d or a non-numeric value to %f
Forget to escape % as %% when you need a literal percent
Mix up argument order relative to specifiers
Chain excessive + when a format template would be clearer
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about format()
Use these points whenever you build formatted strings in Java.
5
Core concepts
📄01
Template
Placeholders + text.
Purpose
⚙️02
Static
String.format().
Syntax
🔢03
%s %d %f
Core specifiers.
API
💰04
Precision
%.2f decimals.
Display
🖥️05
vs printf
Return vs print.
Compare
❓ Frequently Asked Questions
String.format(format, args...) builds a new String by replacing placeholders in the format string with the supplied arguments. It works like printf-style formatting and returns the finished text.
Yes. You call it on the String class: String.format("Hello, %s", name). You do not call it on an existing string variable to format that string's content.
%s inserts a string, %d inserts an integer, %f inserts a floating-point number. You can add precision such as %.2f for two decimal places and width such as %05d for zero-padded numbers.
Concatenation with + joins pieces directly. format() uses a template with placeholders, which is clearer when mixing text, numbers, and fixed decimal places—especially for reports and log messages.
IllegalFormatException if the format string is invalid or the argument type does not match the specifier (for example, passing a String where %d expects an integer).
System.out.printf(format, args) prints formatted output. String.format(format, args) returns the same formatted text as a String so you can store it, return it, or log it.