DEV Community

hiro
hiro

Posted on • Originally published at b.0218.jp

[Java] How to Insert Line Breaks in a String

Differences in Line Break Codes

The line break code can vary depending on the operating system.

Windows UNIX
\r\n \n

Examples

Line breaks can be achieved by directly including the line break code in the string.

String text = "Hello \r\nWorld";
System.out.println(text);
Enter fullscreen mode Exit fullscreen mode
Hello
World
Enter fullscreen mode Exit fullscreen mode

Example Absorbing Environmental Dependencies

Java offers a standard feature to obtain environment-independent line break codes.

By using System.getProperty("line.separator") as shown below, you can get the appropriate line break code for the execution environment.

public static final String LINE_SEPARATOR = System.getProperty("line.separator");

String test = "Hello" + LINE_SEPARATOR + "World";
System.out.println(test);
Enter fullscreen mode Exit fullscreen mode

It's recommended to use System.getProperty("line.separator") for line breaks in Java.

Top comments (1)

Collapse
 
ozkanpakdil profile image
özkan pakdil • Edited

also you can use System.lineSeperator() function directly.