How to use printf() and format() in Java
format()
is a static method of the String
class that is used to format a string with placeholders for values that will be inserted into the string. The placeholders are specified using the %
character followed by a format specifier.
Here is an example of how to use format()
:
int x = 10;
double y = 3.14;
String s = "Hello";
String output = String.format("x = %d, y = %.2f, s = %s", x, y, s);
System.out.println(output); // prints "x = 10, y = 3.14, s = Hello"
printf()
is a method of the PrintStream
class (which includes System.out
) that is used to print a formatted string to the console. It works in a similar way to format()
, but it also prints the formatted string to the console.
Here is an example of how to use printf()
:
int x = 10;
double y = 3.14;
String s = "Hello";
System.out.printf("x = %d, y = %.2f, s = %s", x, y, s); // prints "x = 10, y = 3.14, s = Hello"
The format specifiers in format()
and printf()
can be used to specify the data type of the values being inserted into the string, as well as the width and precision of the values. For example, the %d
specifier is used to insert an integer value, while the %.2f
specifier is used to insert a floating-point value with a precision of 2 decimal places.
It's worth noting that format()
and printf()
are just two of the many ways to format strings in Java. There are also other options available, such as using the String.format()
method, the MessageFormat
class, and the java.util.Formatter
class.