The String.format() method in Java is used to create a formatted string by specifying a format string and providing arguments that will replace the format specifiers in the format string. Here's how it works:
- Format String: This is a string that contains format specifiers (like
%s,%d, etc.) that define how the arguments should be formatted. - Arguments: These are the values that will replace the format specifiers in the format string.
Example
Here's a simple example demonstrating the use of String.format():
public class FormatExample {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
String formattedString = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formattedString); // Output: My name is Alice and I am 30 years old.
}
}
In this example:
%sis used for a string (the name).%dis used for an integer (the age).
You can use various format specifiers to format different types of data according to your needs.
