Search code examples
javaprintfsystem.outprintstream

What is the benefit of using System.out.print over System.out.printf?


I have a question similar to Is there a good reason to use "printf" instead of "print" in java?. That question asks and is answered about the benefits of using System.out.print over System.out.printf. I am curious about the benefits to using System.out.print over System.out.printf in the first place.

In my experience, I see System.out.print used drastically more often than System.out.printf.

With System.out.printf, it is more readable when formatting numbers. You still have the syntactic sugar of concatenating strings with +'s, as seen in the second System.out. System.out.printf also returns a PrintStream in case you want to do anything with it.

Examples:

int hour = 6;
int minutes = 5;
int seconds = 4;
System.out.printf("Time: %d:%02d:%02d", hour, minutes, seconds);
System.out.printf("Time: " + hour + ":%02d:%02d", minutes, seconds);
System.out.print("Time: " + hour + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
//Output for each line:  Time: 6:05:04

System.out.printf("Print something!");
System.out.print("Print something!");
//Output for each line:  "Print something!"

System.out.printf("End a line\n");
System.out.println("End a line");
//Output for each line:  End a line [followed by a line break]

String x = "a variable";
System.out.printf("Add %s", x);
System.out.printf("Add " + x);
System.out.print("Add " + x);
//Output for each line:  Add a variable

So aside from (I think) majority of Java programmers using System.out.print, what is the benefit to it over System.out.printf? Is there a noticeable difference in memory or time efficiency?


Solution

  • print with string concatenation will be marginally more efficient than printf. With print, you the developer are determining at compilation time where the values need to be inserted into the string, but with printf, you're asking the JRE to parse your format string and insert the values at runtime. Unless you're doing a large amount of printing, this is likely to be a negligible difference, so you should go with whatever is easiest to maintain.