EN
Java – how to add new line char in String?
10 points
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 |
xxxxxxxxxx
1
public class JavaAddNewLineExample1 {
2
3
public static void main(String[] args) {
4
5
String oneLiner = "This is example";
6
7
// add new line character - \n
8
String withNewLines = "This\nis\nexample";
9
10
System.out.println(oneLiner);
11
System.out.println(withNewLines);
12
}
13
}
Output:
xxxxxxxxxx
1
This is example
2
This
3
is
4
example
xxxxxxxxxx
1
public class JavaAddNewLineExample2 {
2
3
public static void main(String[] args) {
4
5
String oneLiner = "This is example";
6
7
// add new line character
8
// \r\n - on Windows
9
// \n - on Linux
10
String withNewLines = "This "
11
+ System.lineSeparator() + "is"
12
+ System.lineSeparator() + "example";
13
14
System.out.println(oneLiner);
15
System.out.println(withNewLines);
16
}
17
}
Output:
xxxxxxxxxx
1
This is example
2
This
3
is
4
example