The String.format()
method in Java allows you to create formatted strings using placeholders. It is similar to printf
but returns the formatted string instead of printing it. Placeholders, such as %s
for strings, %d
for integers, and %f
for floating-point numbers, specify the desired format. For example, String.format("Hello, %s!", "John")
returns “Hello, John!”.
You can also control precision, width, and alignment, such as %.2f
for two decimal places or %10s
for right-aligned text. It is commonly used for creating user-friendly outputs, logging, and constructing strings dynamically with specific formatting requirements.