Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between PrintWriter.printf and PrintWriter.format methods

Tags:

java

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.

like image 607
Amit G Avatar asked Oct 14 '25 20:10

Amit G


2 Answers

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.

like image 51
coobird Avatar answered Oct 17 '25 10:10

coobird


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);
 }
like image 38
IRBMe Avatar answered Oct 17 '25 08:10

IRBMe