In Java, the \n
characters are used to represent a newline in a string literal. For example:
String s = "Hello\nWorld"; System.out.println(s);
This will output the following to the console:
Hello World
The \n
characters are treated as line breaks, causing the text following them to be printed on a new line.
You can also use the \r
character to represent a carriage return, or the \r\n
sequence to represent a combination of a carriage return and a newline.
Here is an example that demonstrates how to use \r
and \r\n
:
String s1 = "Hello\rWorld"; System.out.println(s1); String s2 = "Hello\r\nWorld"; System.out.println(s2);
This will output the following to the console:
World Hello World