I’m doing Java since 1999, and it is my daily language since 2001. But still there are gems that I learn each day! Today it is the benefits of System.out.printf()
. Yes, printf()
, not println()
!
This 1.5-introduced method is rather clever, as it combines the use of System.out.println()
(which, frankly spoken, still is my workhorse for quick debugging, even in times of all that nice IDEs and tools) with String.format()
. Now comes the nice thing: Not only it is more convenient to write and read, it also is optimized for streaming (i. e. repeated) use (as it is implemented by PrintStream
), hence imposes less GC stress and results in improved performance also. Nice!
BTW, with printf
one has to explicitly append the EOL character. As System.out
uses platform-specific settings, using \n
would be wrong (it produces exactly LF). Using %n
instead will produce the correct platform-specific EOL character sequence!
System.out.printf("Line %d%nLine%d%n", 1, 2);
Sometimes it simply is the small things that make my day. 🙂
-Markus