This article will demonstrate the Java string format() method along with the practical implementation.
What is Java String format() Method With Examples?
The Java String format() method allows users to easily format and display data in a customizable way.
The syntax for the format() method is as follows:
In the above syntax, the first argument is a string that holds placeholders for the dynamic values. The placeholders are represented by % symbols followed by a format specifier, which defines the type and format of the corresponding argument.
The remaining arguments are the dynamic values that are substituted into the placeholders. These can be any Java objects, including numbers, strings, dates, and other objects. Here are some examples of using the format() method:
An example is considered in which the “format” string contains three placeholders. Let execute the code:
The description of the above code is given below:
- The first placeholder is %s, which indicates a string value.
- The second placeholder is %d, which indicates an integer value.
- The third placeholder is %.2f, which indicates a floating-point value.
- The corresponding arguments are the “name”, “age”, and “salary” variables, respectively
The output shows that arguments are the “name”, “age”, and “salary” variables are in a format a string.
Another example is conducted by following the format string containing two placeholders. Let follow the below code:
The description of the above code is mentioned below:
- The first placeholder is %d, which indicates an integer value.
- The second placeholder is %s, which indicates a string value.
- The corresponding arguments are the num variable and the result of calling the toBinaryString() method on the num variable.
The above display shows the binary of 42 numbers in the terminal.
Let execute another example in which the format string contains one placeholder:
The explanation of the code is given below:
- The “format” string contains one placeholder, which is %1$tA, %1$tB %1$te, %1$tY.
- This placeholder indicates a date value, with the day of the week, month, day of the month, and year components separated by commas.
- The corresponding argument is the parsedDate variable, which is a LocalDate object that represents the date parsed from the date string.
The output shows day of the week, month, date, and year.
The format() method is a powerful tool for constructing formatted strings in Java. By using a combination of format “specifiers” and “arguments”, users can create dynamic strings that are tailored to the specific needs. With the format() method, users can manage the alignment, width, and precision of the output for generating well-formatted strings. This article has explained the format() method along with different examples.