Languages
[Edit]
EN

Java – how to add new line char in String?

10 points
Created by:
Marcin
2465

1. Overview

In java we can use direct new line char or we can use method which gives us platform dependent new line character.

In this post we have 2 examples.

First one with new line character used explicitly.

Second one uses most popular method in java to get platform dependent new line character System.lineSeparator().

New line character on most popular operating systems

Operating System Name New line character
Windows \r\n
Linux / Unix \n
MacOS \n

2. Example 1

public class JavaAddNewLineExample1 {

    public static void main(String[] args) {

        String oneLiner = "This is example";

        // add new line character - \n
        String withNewLines = "This\nis\nexample";

        System.out.println(oneLiner);
        System.out.println(withNewLines);
    }
}

Output:

This is example
This
is
example

3. Example 2

public class JavaAddNewLineExample2 {

    public static void main(String[] args) {

        String oneLiner = "This is example";

        // add new line character
        // \r\n - on Windows
        // \n   - on Linux
        String withNewLines = "This "
                + System.lineSeparator() + "is"
                + System.lineSeparator() + "example";

        System.out.println(oneLiner);
        System.out.println(withNewLines);
    }
}

Output:

This is example
This
is
example

See also

  1. Java - how to get new line character for given platform eg Windows, Linux or MacOS - platform dependent?

References

  1. Newline - wiki
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.