String.format() lets you build strings with placeholders that get filled in at runtime. The syntax uses % codes as format specifiers.
String name = "Alice";
int age = 30;
String msg = String.format("Name: %s, Age: %d", name, age);
System.out.println(msg);
This prints Name: Alice, Age: 30. The %s placeholder accepts a string. The %d placeholder accepts an integer. The arguments fill in left to right.
For floating-point numbers, use %f. To limit decimal places, add a precision: %.2f rounds to decimal places.
double price = 9.99;
System.out.println(String.format("Price: $%.2f", price));
This prints Price: .99. You can also use System.out.printf(), which works the same way but prints directly to the console without returning a string. Choose String.format() when you need the result stored in a variable for later use.