2

I was referring to this question and understood that \n moves the cursor to next line without resetting it while \r resets the cursor but not move it to next line. And \r\n used as a new line char in Windows. So just out of curiosity, I assigned \r\n and \n\r to strings along with some other value in Java and printed them in console in my Windows environment.

System.out.println("ABC\r\nDEF");
System.out.println("ABC\n\rDEF");

Output 1:

ABC
DEF

As per my understanding, here \r just did reset the cursor and moved it at the beginning of the same line (line 1) and \n advanced it to the next line (line 2). Hence DEF printed in new line.

Output 2:

ABC

DEF

But I am not able to understand the Output 2. I assume this one should be same as output 1 because if \n advances the cursor to next line (line 2) and then if \r reset it and puts it at the beginning of the same line (line 2 in this case may be) then why DEF is not printed at line 2?

Edit:

This is the additional question which is not covered in this or this

Community
  • 1
  • 1
Ravi Amlani
  • 72
  • 1
  • 9
  • http://stackoverflow.com/questions/15433188/r-n-r-n-what-is-the-difference-between-them – XtremeBaumer Apr 25 '17 at 09:58
  • @Obenland this extra question isn't asked or answered there. – slim Apr 25 '17 at 10:02
  • @Obenland your link only mentions that Windows supports `\r\n`. But Windows also supports only `\n` and only `\r`. Hence I got this question and which is not answered in the link you mentioned or XtremeBaumer mentioned. – Ravi Amlani Apr 25 '17 at 10:09

2 Answers2

5

This is nothing to do with Java and everything to do with the console/terminal/etc. that's converting the output to a display.

In Windows command windows, the canonical "end-of-line" encoding is \r\n. Windows treats this as a single entity.

Although the historical reason for this is a teleprinter's carriage return (move the print head to the left) and newline (advance the paper one line), in Windows \r\n is one "thing" as far as display is concerned.

\n\r is not recognised as one "thing" in the same way. But it handles each character by advancing by a line.

slim
  • 38,247
  • 12
  • 91
  • 123
  • Thanks @slim for the answer. But if `\n\r` is processed as 2 separate things and I also tried passing `\n` alone and `\r` alone and both of them are able to print chars on new line. So are we used to pass `\r\n` together just to follow the preset standards or can we also use one of `\n` or `\r` alone also? Is it considered as a bad practice? – Ravi Amlani Apr 25 '17 at 10:38
3

The difference is that \n\r doesn't exist, but \r\n does. The reason, way back in the day, is that hardware like the ASR-33 that had a 'carriage' could overlap the carriage return with the line feed if the carriage return came first. Using \n\r would have been extremely inefficient, so nobody did it.

So don't do it.

user207421
  • 298,294
  • 41
  • 291
  • 462