System.out.printf vs System.out.format
JavaFormatPrintfJava Problem Overview
Are System.out.printf
and System.out.format
totally the same or perhaps they differ in somehow?
Java Solutions
Solution 1 - Java
System.out
is a PrintStream
, and quoting the javadoc for PrintStream.printf
> An invocation of this method of the
> form out.printf(l, format, args)
> behaves in exactly the same way as the invocation
> out.format(l, format, args)
Solution 2 - Java
The actual implementation of both printf overloaded forms
public PrintStream printf(Locale l, String format, Object ... args) {
return format(l, format, args);
}
and
public PrintStream printf(String format, Object ... args) {
return format(format, args);
}
uses the format method's overloaded forms
public PrintStream format(Locale l, String format, Object ... args)
and
public PrintStream format(String format, Object ... args)
respectively.
Solution 3 - Java
No difference.They both behave the same.
Solution 4 - Java
The key difference between printf
and format
methods is:
- printf: prints the formatted String into console much like System.out.println() but
- format: method return a formatted String, which you can store or use the way you want.
Otherwise nature of use is different according to their functionalities. An example to add leading zeros to a number:
int num = 5;
String str = String.format("%03d", num); // 005
System.out.printf("Original number %d, leading with zero : %s", num, str);
// Original number 5, leading with zero : 005