The String.format()
method in Java is used to create formatted strings, similar to printf()
. It replaces placeholders in a format string with specified values.
Syntax:
java
String.format(String format, Object... args);
Example:
java
String name = "Alice";
int age = 25;
String result = String.format("Name: %s, Age: %d", name, age);
System.out.println(result);
// Output: Name: Alice, Age: 25
Common Placeholders:
%s
– String%d
– Integer%f
– Floating-point number%n
– Newline
String.format()
is ideal for building readable, dynamic text.