Is there any difference between the Java PrintWriter
methods printf
and format
?
The doc says printf
is a convenience method but if it behaves exactly as format
, so I don't understand what's convenient about it.
A convenience method is as the name implies -- it exists just for the sake of convenience, not necessarily for function.
One common case where convenience methods exist is for methods which have multiple arguments, but some arguments are used in a particular manner. Many times, the same method will be overloaded with different arguments.
Take the following code:
public void myMethod(int value, boolean hasImportance) {
// do something.
}
public void myMethod(int value) {
myMethod(value, true);
}
In the above example, the myMethod(int)
method can be thought of as a convenience method for myMethod(int, boolean)
, as it provides a default argument for one of its parameters.
In the case of PrintWriter.printf
, it is basically invoking PrintWriter.format
, but just provides an alternate way of invoking the format
method.
Probably the justification behind the creation of the printf
method as a convenience method is because the printf
method's naming conveys the meaning that one is trying to output with formatting rather than just format
, which doesn't convey the intent that one is trying to perform a output with formatting.
According to this, they are the same
/**
...
* <p> An invocation of this method of the form <tt>out.printf(format,
* args)</tt> behaves in exactly the same way as the invocation
*
* <pre>
* out.format(format, args) </pre>
...
*/
public PrintWriter printf(String format, Object ... args) {
return format(format, args);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With