0

I was going over different escape sequences in Java, and was wondering if anyone knows if there is a functional different between \n and \r in java. The \n is for a newline and the \r is for a carriage return, but does one have an advantage over the other?

  • Possible duplicate of [Difference between \n and \r?](https://stackoverflow.com/questions/1761051/difference-between-n-and-r) – Sudhir Ojha Feb 06 '20 at 10:49
  • Check out this SO question: [link](https://stackoverflow.com/questions/1761051/difference-between-n-and-r) – curiousMinded Feb 06 '20 at 10:50
  • Yes, `\r` doesn't move the carriage down to a new line. It will only move it to the beginning of the same line you're on. – marstran Feb 06 '20 at 10:50
  • Java doesn't care, your OS does. Java will use the relevant linefeed terminator(s) when you use `System.out.println()`, and when crafting `String`s that contain linefeeds you will want to use `System.lineSeparator()` to use the relevant linefeed terminator(s) if you want to be portable. Ideally you should never write any `\n` or `\r` in your Java code. – Aaron Feb 06 '20 at 11:01

2 Answers2

1

Those characters have a historical meaning due to (tele)typewriters:

  • Carriage return (\r): reset the position within the line to the start. This was used sometime to type multiple characters on top of each other, such as when underlining characters with _ or typing accent characters (e.g. typing " on a to get ä).
  • Line feed (\n): increase the vertical position by one line (retaining the offset within the line).

With (tele)typewriters, those were two different operations/instructions, and starting a new line would be the combination of both: Carriage return and line feed (\r\n).

In the ASCII character set, you'll encounter other characters that are no real characters of written language, but rather instructions, often for teletypewriters (such as bell, enquiry, acknowledgment, form feed, vertical tab, ...)

On windows systems, you often encounter the combination (\r\n), whereas on other platforms the line feed has a new semantic of also doing a line feed (so only \n is used) - this is the new state of the art.

Peter Walser
  • 15,208
  • 4
  • 51
  • 78
0

Use \n to be safe.

Also, What is the difference between a "line feed" and a "carriage return"?

You could see the equivalent of carriage return, in modern days, as the pressing of the 'home' button on our keyboards.

N Katz
  • 67
  • 7