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.
Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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:
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.