I am new to java, and was wondering why would someone use System.out.println() to change line instead of just putting "\n" inside the parentheses. Are there any differences between these two?
3 Answers
Consult the Javadoc (emphasis mine):
[
PrintStream.println
] Terminates the current line by writing the line separator string. The line separator string is defined by the system propertyline.separator
, and is not necessarily a single newline character ('\n'
).
For instance, Windows uses \r\n
as its default newline separator.
Additionally, having to append whichever newline to the thing your are printing is not only verbose (crufty, one might say), but inefficient.
Consider replacing println("a really big string")
with print("a really big string" + "\n")
. Let's pretend that the really big string actually is really big, and not a compile-time constant. Because Strings are immutable, a new string has to be created, entirely copying that really big string and appending the newline. Now, for the sake of printing something (once), you had to go to the effort of copying a really big thing.
Also consider printing non-strings, e.g. println(0)
with print(0 + "\n")
. That's now invoking an entirely different overload (println(String)
instead of println(int)
), and it's having to construct a String where previously it could use a specialized efficient method for printing simple int
s.
Both of these efficiency issues are (or at least can be) avoided by providing methods which handle appending the newline internally.

- 137,514
- 11
- 162
- 243
-
2On top of this, adding a newline is often what you want so it's nice to have it included automatically instead of needing to add it to all your strings. – puhlen Jul 11 '17 at 14:18
new line in diffrent operation system are diffrent for example
Unix based systems=> "\n"
windows => "\r\n"
and some other machines used just a "\r". (Commodore, Apple II, Mac OS prior to OS X, etc..)
if you don't use println
you have to manage these by yourself or get it by system propery like this
System.getProperty("line.separator");

- 1,776
- 2
- 17
- 27
As indicated in the comments, simply appending \n
won't work in all environments (e.g. Windows). If you want to append the correct line ending "manually," you need to retrieve it with either
System.getProperty("line.separator");
Or, in Java 7:
System.lineSeparator()
See also this answer (which was the source of those two lines of code).

- 11,977
- 56
- 49
- 78