may i know what is the difference between the two in java? i am reading a book and it can either use both of it to display strings.
String.format
returns a formatted string. System.out.printf
also prints the formatted string.
String.format
returns a new String, while System.out.printf
just displays the newly formatted String to System.out, sometimes known as the console.
These two snippets of code are functionally equivalent:
String formattedString = String.format("%d is my favorite number", 42);
System.out.print(formattedString);
and
System.out.printf("%d is my favorite number", 42);
These two methods exhibit the exact same behavior. We can use the format(...) with String, Java.util.Formatter (J2SE 5) and also with PrintWriter.
The first one writes to the stdout and the second one returns a String
object.
Which to use depends on the sole purpose. If you want to display the string in the stdout (console), then use the first. If you want to get a handle to the formatted string to use further in the code, then use the second.
String.format
formats strings, doesn't display them. I think you mean System.out.println(String.format("......", ....))
or some similar construct ?