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.
[toc]
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.

package org.arpit.java2blog.Java2blogPrograms;

public class EndLineCharacterMain {

    public static void main(String[] args)
    {
        // Should be used in Linux OS
        String str1 = "Hello"+ "\n" +"world";
        System.out.println(str1);

        // Should be used in Windows
        String str2 = "Hello"+ "\r\n" +"world";
        System.out.println(str2);
    }
}

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.

package org.arpit.java2blog.Java2blogPrograms;

public class EndLineCharacterMain {

    public static void main(String[] args)
    {
        String str1 = "Hello"+ System.lineSeparator() +"world";
        System.out.println(str1);

        String str2 = "Hello"+ System.getProperty("line.separator") +"world";
        System.out.println(str2);
    }
}

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.