views:

287

answers:

3

I'm reading Effective Java and it uses %n for the newline character everywhere. I have used \n rather successfully for newline in Java programs.

Which is the 'correct' one? What's wrong with '\n' ? Why did Java change this C convention?

+14  A: 

From a quick google:

There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas"\n" is not.

source

Bill K
Want to know something trippy? I just got the "Enlightened" badge for this so I came back to look at it but I don't remember answering this at all... Damn my memory sucks, that was less than a year ago.
Bill K
+5  A: 

%n is portable accross platforms \n is not.

See the formatting string syntax in the reference documentation:

'n' line separator The result is the platform-specific line separator

Gregory Pakosz
+3  A: 

While "\n" is the correct newline character for Unix-based systems, other systems may use different characters to represent the end of a line. In particular, Windows system use "\r\n", and early MacOS systems used "\r".

By using %n in your format string, you tell Java to use the value returned by System.getProperty("line.separator"), which is the line separator for the current system.

Craig Putnam