Java – Add new line in String

Different operating system has a different new line or line separator string:

  • UNIX, Linux or Mac OSX = \n
  • Windows = \r\n
NewLineExample.java

package com.mkyong;

public class NewLineExample {

    public static void main(String[] args) {

        String original = "Hello World Java";

        System.out.println(original);

		// add new line
        String originalNewLine = "Hello\nWorld\nJava";

        System.out.println(originalNewLine);
    }

}

Output


Hello World Java

Hello
World
Java

We can also use the Java 1.7 System.lineSeparator to return the system-dependent new line:

NewLineExample2.java

package com.mkyong;

public class NewLineExample2 {

    public static void main(String[] args) {

        String original = "Hello World Java";

        System.out.println(original);

        String originalNewLine = "Hello"
                + System.lineSeparator() + "World"
                + System.lineSeparator() + "Java";

        System.out.println(originalNewLine);
    }

}

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments