Java String fomat() Method
Last Updated :
11 Apr, 2025
In Java, the String.format() method allows us to create a formatted string using a specified format string and arguments. We can concatenate the strings using this method, and at the same time, we can format the output with options such as width, alignment, decimal places, and more.
Example: In the example below, we will use the String.format() method to concatenate a string and format the output with a placeholder.
Java
// Java program to demonstrate working of format() method
class Geeks
{
public static void main(String args[]) {
String s = "GeeksforGeeks";
// Concatenate string
// using format()
String res = String.format("Welcome to %s!", s);
System.out.println(res);
}
}
OutputWelcome to GeeksforGeeks!
Explanation: In the above example, the format() method of the String class is used to insert the value of “s” into the formatted string. The placeholder %s is replaced with the string value.
There are two main versions of the format() method:
public static String format(Locale locale, String form, Object… args);
public static String format(String format, Object… args);
Parameters:
- locale: The locale value to be applied (optional).
- format: The format string that defines how the output should look.
- args: The arguments to be formatted as per the format string.
Return Type: The method returns a formatted string.
Exceptions:
Example: Using String.format() method to show concatinate the two floating values of given variable using %2f.
Java
// Java program to demonstrate floating-point
// formatting with format()
class Geeks
{
public static void main(String args[]) {
double d = 9876.54321;
// Format the float number with
// 2 decimal places
String s = String.format("Formatted Value: %.2f", d);
System.out.println(s);
}
}
OutputFormatted Value: 9876.54
Explanation: In this example, a floating-point number 9876.54321 is formatted to show only two decimal places using String.format(). The placeholder %.2f ensures that the value is rounded to two decimal places and displayed.
- %2f: The f specifier is for floating-point numbers, and .2 means the number should be rounded to two decimal places.
- The formatted value 9876.54 is printed with the label Formatted Value, by providing a more readable output.
In this example, we will specify the formatting options like grouping digits, for example, for large numbers and controlling the number of decimal places.
Example: Using String.format() method for advance formatting with decimal and thousands seperator.
Java
// Java program to demonstrate
// advanced formatting using format() method
class Geeks
{
public static void main(String args[]) {
// Define a double value
// representing a price
double d = 12345.6789;
// Format the price with thousands
// separator and two decimal places
String s = String.format("%1$,10.2f", d);
System.out.println("Formatted Price: " + s);
}
}
OutputFormatted Price: 12,345.68
Explanation: In the above example, it formats the floating-point number with a thousands separator and two decimal places. The number 12345.6789 is formatted to 12,345.68.
In the placeholder,
- %1$: It refers to the first argument (d), the price value.
- ,: It groups digits with a comma as a thousands separator.
- 10.2f: It ensures that the floating-point number takes at least 10 characters, with 2 decimal places.
In this example, we will combine multiple formatting components to customize how the arguments should appear.
Example: Using String.format() method with complex placeholder formatting.
Java
// Java program to demonstrate
// complex placeholder formatting
class Geeks
{
public static void main(String args[]) {
// Declare a double value
// representing the distance
double d = 1500.75;
// Declare a string value
// representing the unit of measurement
String s = "kilometers";
// Correct the argument order to match the format specifiers
String res = String.format("%1$,7.1f %2$s", d, s);
System.out.println(res);
}
}
Explanation: In the above example, it formats a floating-point number and a string using placeholders in the String.format() method. The number 1500.75 is formatted with a comma separator and one decimal place, and the string “kilometers” is added next to it.
In the placeholder,
- %2$: Refers to the second argument i.e. “d” the distance.
- ,: Groups digits with a comma as a thousands separator.
- 7.1f: This ensures that the floating-point number takes at least 7 characters in total, with 1 decimal place.
- %1$s: It refers to the first argument i.e. “s” the unit and formats it as a string.
The String.format() method uses format specifiers to format various types of data. Below are some common specifiers:
Format Specifier
| Data Type | Output or Return value |
---|
%a
| floating point | Returns a Hex output of floating point number |
---|
%b
| any type | True or False |
---|
%c
| character | Unicode character |
---|
%d
| integer | Decimal Integer |
---|
%e
| floating point | a decimal number in scientific notation |
---|
%f
| floating point | decimal number |
---|
%g
| floating point | decimal number, possibly in scientific notation depending on the precision and value |
---|
%h
| any type | Hex String of value from hashCode() method |
---|
%n
| None | Platform-specific line separator |
---|
%o
| integer | Octal number |
---|
%s
| any type | String value |
---|
%t
| Date/Time | %t is the prefix for Date/Time conversions. |
---|
%x
| integer | Hex string |
---|
Similar Reads
Boolean toString() Method in Java
In Java, the toString() method of the Boolean class is a built-in method to return the Boolean value in string format. The Boolean class is a part of java.lang package. This method is useful when we want the output in the string format in places like text fields, console output, or simple text forma
2 min read
Java String valueOf() Method
The valueOf() method of the String class in Java helps to convert various data types like integers, floats, booleans, and objects into their string representations. It makes it simple to work with string manipulation, logging, and displaying data efficiently. Example: To convert a number into text f
3 min read
Object toString() Method in Java
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class, henceforth, it is a child of the Object class. If a class does not extend any other class then it is a direct child class of Object, and if it extends another class, then it is
3 min read
Java Vector elementAt() Method
In Java, the elementAt() method is used to fetch or retrieve an element at a specific index from a Vector. It allows to access elements in the vector by providing the index, which is zero-based. Example 1: Here, we use the elementAt() method to retrieve an element at a specified index with an Intege
2 min read
DecimalFormat toPattern() method in Java
The toPattern() method of the DecimalFormat class in Java is used to convert the format of the current pattern of this DecimalFormat to a string format. This converted string represents the pattern which is used to format the current state of this DecimalFormat instance. Syntax: public String toPatt
2 min read
YearMonth compareTo() method in Java
The compareTo() method of YearMonth class in Java is used to compare two YearMonth objects. It compares this YearMonth object to the YearMonth object passed to it as parameter. The comparison between the two YearMonth instances is first done on the value of Year and then on the Month. Syntax: public
2 min read
HashSet toString() method in Java with Example
The toString() method of Java HashSet is used to return a string representation of the elements of the Collection. The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used m
2 min read
Date toString() method in Java with Examples
The toString() method of Java Date class converts this date object into a String in form "dow mon dd hh:mm:ss zzz yyy". This method overrides toString in class object. Syntax: public String toString() Parameters: The function does not accept any parameter. Return Value: It method returns a string re
2 min read
Instant toString() method in Java with Examples
The toString() method of Instant class returns string representation of this instant using ISO-8601 representation and format used is the same as DateTimeFormatter.ISO_INSTANT. Syntax: public String toString() Returns: This method returns an ISO-8601 representation of this instant, not null. Below p
1 min read
SortedSet first() method in Java
The first() method of SortedSet interface in Java is used toReturns the first i.e., the lowest element currently in this set.Syntax: E first() Where, E is the type of element maintained by this Set.Parameters: This function does not accepts any parameter.Return Value: It returns the first or the low
2 min read