Is there any difference in these four ways of formatting the same data?
// Solution 1
System.out.printf("%.1\n",10.99f);
// Solution 2
System.out.format("%.1\n",10.99f);
// Solution 3
System.out.print(String.format("%.1\n",10.99f));
// Solution 4
Formatter formatter = new Formatter();
System.out.print(formatter.format("%.1\n",10.99f));
formatter.close();
The first two are exactly the same, since printf
is implemented as (source)
public PrintStream printf(String format, Object ... args) {
return format(format, args);
}
The latter two are also exactly the same, since String.format
is implemented as (source)
public static String format(String format, Object ... args) {
return new Formatter().format(format, args).toString();
}
Finally, the 2nd and the 4th are more or less the same, as can be seen from the implementation of PrintStream.format
(source). Under the hood, it also creates a new
Formatter
(if needed) and calls format
on that Formatter
.
public PrintStream format(String format, Object ... args) {
try {
synchronized (this) {
ensureOpen();
if ((formatter == null)
|| (formatter.locale() != Locale.getDefault()))
formatter = new Formatter((Appendable) this);
formatter.format(Locale.getDefault(), format, args);
}
} catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
} catch (IOException x) {
trouble = true;
}
return this;
}
System.out
is a PrintStream
For detail follow this Link : Details about various format
An invocation of this method of the form
out.printf(Locale l, String format,Object... args)
behaves in exactly the same way as the invocation
out.format(Locale l,String format,Object... args)
So 1 & 2 are same there is not any difference b/w them. and 3 & 4 are almost same only compilation time difference will be there if compared with 1 & 2.
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