String formatting is a powerful feature in Java that allows you to create dynamic and customized output by combining text and variables. It provides a flexible way to format and display data in a specific format, making it easier to present information in a clear and readable manner.
The primary method for string formatting in Java is the printf()
and format()
methods, which are part of the System
class. These methods allow you to specify a format string that defines the layout and appearance of the output, and then provide the values to be inserted into the format string.
Here's an example of how to use the printf()
method to format a string:
int age = 25;
double height = 1.75;
System.out.printf("My name is John, I am %d years old and my height is %.2f meters.", age, height);
This will output:
My name is John, I am 25 years old and my height is 1.75 meters.
In the format string, the %d
placeholder is used for the integer value (age), and the %.2f
placeholder is used for the floating-point value (height), with the .2
specifying that the number should be displayed with two decimal places.
The format()
method works in a similar way, but it returns the formatted string instead of printing it directly to the console. This can be useful when you need to store the formatted output in a variable for further processing.
String formattedString = String.format("My name is John, I am %d years old and my height is %.2f meters.", age, height);
System.out.println(formattedString);
This will output the same result as the previous example.
Overall, string formatting in Java is a versatile and powerful tool that can help you create clear and informative output, making it easier to communicate information to users or other parts of your application.