Basic Usage
The basic syntax for using the String.format()
method is as follows:
String.format(String format, Object... args)
The format
parameter is the string that contains the format specifiers, and the args
parameter is a variable-length argument list that provides the values to be inserted into the format string.
Here's an example of using the String.format()
method to format a string with different data types:
String name = "LabEx";
int age = 25;
double height = 1.75;
String formattedString = String.format("My name is %s, I'm %d years old, and I'm %.2f meters tall.", name, age, height);
System.out.println(formattedString);
Output:
My name is LabEx, I'm 25 years old, and I'm 1.75 meters tall.
The String.format()
method supports a variety of format specifiers, each representing a different data type. Here are some common format specifiers:
Specifier |
Description |
%s |
Formats the argument as a string |
%d |
Formats the argument as a decimal integer |
%f |
Formats the argument as a floating-point number |
%c |
Formats the argument as a character |
%b |
Formats the argument as a boolean value |
You can also specify additional formatting options, such as field width, alignment, and precision, by using the following syntax:
%[argument_index$][flags][width][.precision]conversion_character
For example, to right-align a string with a field width of 20 characters, you can use the format specifier %20s
.
The String.format()
method also supports formatting dates and times using the %t
conversion character. Here's an example:
Date currentDate = new Date();
String formattedDate = String.format("Today's date is %tD", currentDate);
System.out.println(formattedDate);
Output:
Today's date is 04/26/23
In this example, the %tD
format specifier is used to format the Date
object as a short date string (MM/dd/yy).
By understanding the various format specifiers and formatting options available in the String.format()
method, you can create highly customized and readable string representations of your data in Java.