The String.format()
method in Java is used to create formatted strings by replacing placeholders with specified values. It is part of the java.lang.String
class and is very useful for formatting output in a structured manner.
Syntax:
format
: A format string containing placeholders.args
: The values to replace the placeholders.
Common Placeholders in Format Strings
Placeholder | Description |
---|---|
%s |
Formats strings. |
%d |
Formats decimal integers. |
%f |
Formats floating-point numbers. |
%n |
Inserts a newline. |
%x |
Formats integers in hexadecimal. |
%o |
Formats integers in octal. |
%b |
Formats boolean values. |
%% |
Prints a % symbol. |
Examples
1. Formatting Strings
2. Formatting Integers
3. Formatting Floating-Point Numbers
4. Multiple Placeholders
5. Formatting Boolean Values
6. Padding and Alignment
- Left-align (
-
) and Right-align (default). - Add width (e.g.,
%10s
for a 10-character-wide string).
7. Hexadecimal and Octal Formatting
Key Points
- The
String.format()
method does not modify the original string; it returns a new formatted string. - It is thread-safe and useful for creating complex formatted output.
- If invalid placeholders are used, it throws a
java.util.IllegalFormatException
.
The String.format()
method is a powerful tool for building dynamic and readable strings in Java.