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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay