Java adding New Line in a String

The string is an essential part of java programming. There is hardly any class we don't need the String.

The new line is part of String.

While doing the programming we need a new line.

In java there are many ways, we can add a new line in the string.

1). Using \n or System.getProperty("line.separator")

The \n or System.getProperty("line.separator") can be used to generate newline for the String.

public class StringAddNewLine1 { public static void main(String[] args) { String str = "Hello World, welcome to java programming."; System.out.println("the original String is\n" + str); System.out.println(str.replaceAll("\\s+", "\n")); System.out.println("\nUsing the System.getProperty()"); System.out.println(str.replaceAll("\\s+", System.getProperty("line.separator"))); } } output: the original String is Hello World, welcome to java programming. Hello World, welcome to java programming. Using the System.getProperty() Hello World, welcome to java programming.

2). Add newLine character while constructing StringBuffer Object

In the case of String buffer, we need to append System.getProperty("line.separator") as newline character.

public class StringBufferNewLine { public static void main(String args[]) { StringBuffer sb1 = new StringBuffer("Welcome to java programming"); sb1.append(System.getProperty("line.separator")); sb1.append("World!!!"); System.out.println(sb1); System.out.println(); StringBuffer sb2 = new StringBuffer("I am crazy"); sb2.append(System.lineSeparator()); sb2.append("Coder."); System.out.println(sb2); } } output: Welcome to java programming World!!! I am crazy Coder.

3). Using Platform-Independent New Lines

If we are using something like System.out.printf or String.format, then the platform-independent new line character, %n, can be used directly within a string as given below.

public class StringAddNewLine { public static void main(String args[]) { String str = "Welcome %n to %n java %n programming."; System.out.printf(str); } } output: Welcome to java programming.

In this article, we have seen Java adding New Line in a String with examples. All source code in the article can be found in the GitHub repository.