In Java, the newline and carriage return characters are both seem to be showing same effect.
What are the actual differences between char literals \n
and \r
in Java?
Note that the above asks about the \n
character, not the newLine()
function on BufferedWriter
, and so this other question isn't relevant.
\n is specifically used to move to a new line, while \r is used for a carriage return, which moves the cursor back to the beginning of the current line. In some cases it's standard to have \r\n such as in telnet applications, which often acts the same as \n.
\r and \n are digital representations of the way you would advance to the next line on a typewriter. \r is a carriage return and \n is a newline (also known as a linefeed). On a typewriter, to go to the start of the new line, you would return the carriage to the leftmost position and then feed the paper up a line.
CR (character : \r, Unicode : U+000D, ASCII : 13, hex : 0x0d) : This is simply the 'r' character. This character is commonly known as 'Carriage Return'. As matter of fact, \r has also has a different meaning. In older printers, \r meant moving the print head back to the start of line and \n meant starting a new line.
'\r' is the representation of the special character CR (carriage return), it moves the cursor to the beginning of the line. '\n'(line feed) moves the cursor to the next line . On windows both are combined as \r\n to indicate an end of line (ie, move the cursor to the beginning of the next line).
\n
is a line feed (LF) character, character code 10. \r
is a carriage return (CR) character, character code 13. What they do differs from system to system. On Windows, for instance, lines in text files are terminated using CR followed immediately by LF (e.g., CRLF). On Unix systems and their derivatives, only LF is used. (Macs prior to Mac OS X used CR, but Mac OS X is a *nix derivative and so uses LF.)
In the old days, LF literally did just a line feed on printers (moving down one line without moving where you are horizonally on the page), and CR similarly moved back to the beginning of the line without moving the paper up, hence some systems (like Windows) sending CR (return to the left-hand side) and LF (and feed the paper up).
Because of all this confusion, some output targets will accept multiple line break sequences, so you could see the same effect from either character depending on what you're outputting to.
\n
is for unix \r
is for mac (before OS X)\r\n
is for windows format
you can also take System.getProperty("line.separator")
it will give you the appropriate to your OS
It depends on which Platform you work. To get the correct result use -
System.getProperty("line.separator")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With