Home Using printlns
Printing and newlines
If you want to print a newline, always do System.out.println()
instead of
System.out.print("\n")
or System.out.println("")
. With a few rare
exceptions, avoid using the \n
or \r
newline escape characters.
The reason why we never print a newline by doing System.out.println("");
is
for one simple reason – it's redundant. Doing System.out.println();
will
do the exact same thing, so why bother adding an extra string when we don't need to?
The reason why we don't permit newlines by doing something like the following is more subtle:
System.out.print("line 1 \n line 2 \n")
Part of the reason why this is forbidden is because it negatively impacts readability. Ideally, we want each line of output to correspond to a single println statement so we can easily scan the method to see how many lines we're printing out, and using newlines interferes with that. We can no longer easily tell how many lines a method could potentially print out.
The other more subtle reason is that the newline character \n
is not
platform-independent – what exactly \n
does will vary from
operating system to operating system and from program to program.
More specifically, if you want a newline in Linux-based operating systems, you need to
use \n
(the newline character). If you want a newline on Macs, you need to use
\r
(the carriage return character). And finally, if you want a newline on
Windows, you need to use \r\n
(carriage return, followed by newline). And of
course, to try and handle this, different IDEs and editors will (inconsistently) attempt to
interpret these different kinds of newlines, adding to the confusion.
Why? Historical happenstance.
Println has none of these issues, and will do the correct thing on all operating
systems. To perform an equivalent task, your program would have to print
System.getProperty("line.separator")
instead of \n
.
There are only two exceptions to the above rule. The first exception is when you're
attempting to dynamically form a string containing newlines. In that case, we have no
choice but to use the \n
character (and for the sake of simplicity, we'll
ignore the fact that \r
exists).
The other exception is when using printf
. We frequently want to use
printf
to print out a single line, like println
, but
printf
will not append a newline to the end of the string for us. As a
consequence, we're ok with you using \n
when using printf
.
We will always tell you when using \n
is ok, so unless instructed otherwise,
avoid using it entirely.