DEV Community

hiro
hiro

Posted on • Originally published at b.0218.jp

1

[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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay