Line breaks in Java can be represented by "\n" (line feed) and "\r" (carriage return), which are usually used to separate text. On Windows, a newline character is represented by "\r\n", while on Unix and Mac it is represented by just "\n".
Java Newline Character
In Java, the newline character can be represented by the following characters:
\n
: Line break character, used to create a new line in the text. \r
: Carriage return character, used to move the cursor to the beginning of the line. Usage of newline characters
Newline characters are usually used to separate text into multiple lines. For example:
<code class="java">System.out.println("Hello\nWorld!");</code>
Output:
<code>Hello World!</code>
Here, the \n
newline character separates the text "Hello" and "World!" into two lines.
Usage of carriage return character
The carriage return character is rarely used alone, and is usually used together with the line feed character (\r\n
), to force the cursor to the beginning of the line and create a new line.
Differences on different platforms
On Windows systems, line breaks are usually represented by a combination of carriage return and line feed characters (\r\n
). On Unix and Mac systems, newlines are usually represented simply by the newline character (\n
).
In Java, you can use System.getProperty("line.separator")
to get the newline character of the current platform.
Example
The following code example demonstrates how to use line feeds and carriage returns:
<code class="java">// 在 Windows 系统上创建新行 String lineSeparator1 = "\r\n"; // 在 Unix 和 Mac 系统上创建新行 String lineSeparator2 = "\n"; // 使用换行符将文本分隔成多行 System.out.println("Hello" + lineSeparator1 + "World!"); System.out.println("Hello" + lineSeparator2 + "World!");</code>
The above is the detailed content of How to express newline character in java. For more information, please follow other related articles on the PHP Chinese website!