Languages
[Edit]
EN

Java – how to add new line char in String?

10 points
Created by:
Marcin
15740

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join