What is the difference between char literals \ n 'and' \ r 'in Java?

In Java, newline and carriage return characters seem like an effect.

What are the actual differences between char literals \n and \r in Java?




Note that the above is asking for the \n character, not the newLine() function on the BufferedWriter , and so this other question doesn't matter.

+51
java newline carriage-return
Feb 13 '12 at 11:58
source share
6 answers

\n is a line character (LF), character code 10. \r is a carriage return (CR) character, character code 13. What they do is different from system to system. On Windows, for example, lines in text files end with CR followed by LF (for example, CRLF). Unix systems and their derivatives use only LF. (Mac before Mac OS X used CR, but Mac OS X is derived from * nix and therefore uses LF.)

In the old days, LF literally did only linear feed on printers (moving down one line without moving where you are horizontally on the page), and CR similarly returned to the beginning of the line without moving paper up, so some systems (like Windows) send CR (return to the left) and LF (and feed the paper up).

Due to all this confusion, some output targets will take multiple line break sequences, so you can see the same effect from any character depending on what you output.

+69
Feb 13 '12 at 12:01
source share

\n for unix
\r for mac
\r\n for Windows format

you can also take System.getProperty("line.separator")

he will provide you with the appropriate OS.

+36
Feb 13 '12 at 12:07
source share

It depends on what platform you are working on. To get the correct result -

 System.getProperty("line.separator") 
+13
Feb 13 2018-12-12T00:
source share

The difference is not specific to Java, but specific to the platform. Historically, UNIX-like operating systems used \n as a newline, some other obsolete OSs used \r , and Windows operating systems used \r\n .

+5
Feb 13 '12 at 12:01
source share

In fact, it depends on what is used to print the result. Usually the result is the same as you say -

Historically, carriage returns are supposed to do what the home button does: return the cursor to the beginning of the line.

\n should give you a new line, but not move the caret.

If you think about old printers, you pretty much think about how the original character set authors think. This is another operation moving the paper feeder and moving the carriage. These two characters express this difference.

+1
Feb 13 2018-12-12T00:
source share

When you print a line in the console (Eclipse), \ n, \ r and \ r \ n have the same effect, they will all give you a new line, but \ n \ r (also \ n \ n, \ r \ r) will give you two new lines: when you write a line to a file, only \ r \ n can give you a new line.

0
Nov 20 '15 at 5:26
source share



All Articles