How is the usage of format in Java?
In Java, the format() method is used to format strings or dates and returns a formatted string. This method is a static method of the String class and can be used in two ways.
- Formatting strings: You can convert a set of variable values into a single string in a specific format using the format() method.
Syntax: String.format(String format, Object… args)
Example: - Output: My name is John, I am 25 years old, and my height is 1.75 meters.
- Format Date: You can use the format() method to convert a date object into a string with a specified format.
Syntax: String.format(String format, Date date)
Example: - Importing the necessary Java libraries, creating a date formatter, getting the current date, formatting it, and then printing it out would result in the output: 2022-09-17.
In the format() method, placeholders in the format string are represented by a percentage sign (%) followed by the appropriate conversion character to indicate the data type to be formatted (such as %s for strings, %d for integers, %f for floating point numbers, etc). Multiple placeholders can be used in the format string, and the variables to be replaced should be passed in the parameters of the format() method in the same order.