Search code examples
javastringnewlinecarriage-returnlinefeed

\r\n vs \n\r what is the difference in their behavior?


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


Solution

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