Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

Java – how to add new line char in String?

0 contributions
10 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more