New line character in java

In this post, we will see about new line character in java and how to add new line character to a String in different operating systems.

Operating systems have different characters to denote the end of the line.

Linux and new mac:
In Linux, the end line is denoted by \n, also known as line feed.

Window:
In windows, end line is denoted by \r\n, also known as Carriage return and line feed (CRLF)

Old mac:
In older version of mac, end line is denoted by \r, also known as Carriage return.

Using \n or \r\n

You can simply add \n in linux and \r\n in window to denote end of the line.

Output:

Hello
world
Hello
world

You can use \n or \r\n but this method is not platform independent, so should not be used.

Using Platform independent line breaks (Recommended)

We can use System.lineSeparator() to separate line in java. It will work in all operating systems.

You can also use System.getProperty("line.separator") to put new line character in String.

Here is the quick snippet to demonstrate it.

Output:

Hello
world
Hello
world

As this method will work in all environment, we should use this method to add new line character in String in java.

That’s all about new line character in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *