.format()
Published Jul 6, 2022
Contribute to Docs
The .format()
method returns a string with additional arguments in a specifically defined format.
Syntax
string.format(String str, ...args);
str
is of typeString
and includes a format specifier.args
is an optional argument, which can be of any data type, to be returned with the first string argument.
Some common format specifiers include:
Format Specifier | Type |
---|---|
%b |
boolean |
%c |
char |
%d |
integer |
%f |
float |
%s |
string |
See Java’s similar .printf()
method for more information on format specifiers.
Note: NullPointerException
will be thrown if the format is null
. An IllegalFormatException
will be thrown if the specifier and argument do not match or the specifier does not exist.
Example
The following example prints out three strings. The first parameter includes a format specifier(s) within a string and has one or two arguments:
class MyFormat {public static void main(String[] args) {String name = "Katara";String job = "bender";System.out.println(String.format("%s is a water %s.", name, job));System.out.println(String.format("%d years!", 100));System.out.println(String.format("%s", "Yip yip."));}}
This outputs the following:
Katara is a water bender.100 years!Yip yip.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.