Tip of the day: System.out.printf()

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. 🙂



About Markus Karg

Java Guru with +30 years of experience in professional software development. I travelled the whole world of IT, starting from Sinclair's great ZX Spectrum 48K, Commodore's 4040, over S/370, PCs since legendary XT, CP/M, VM/ESA, DOS, Windows (remember 3.1?), OS/2 WARP, Linux to Android and iOS... and still coding is my passion, and Java is my favourite drug!
This entry was posted in Java, Programming and tagged , . Bookmark the permalink.