Two strings have no newlines. We can compose them into two lines by concatenating a newline string
. In Java we can add newlines in many ways.
With System
lineSeparator
, we get a platform-dependent newline string
. With Character.SEPARATOR
we access a line break value. Often using "\n" directly is a good choice.
System.lineSeparator
This program uses System.lineSeparator
. On a Windows computer this is equal to \r\n. On a Mac (or Linux) system it equals just "\n."
lineSeparator()
call in between. This composes the strings into two lines.public class Program { public static void main(String[] args) { // ... Use System.lineSeparator. String result = "cat" + System.lineSeparator() + "dog"; System.out.println(result); } }cat dog
LineSeparator
, Windows, UNIXLet us examine the values returned by lineSeparator
. This program, when run on a Windows computer, should display both chars in the lineSeparator
string
.
public class Program { public static void main(String[] args) { String newline = System.lineSeparator(); // Figure out the contents of this string. if (newline.length() == 2) { System.out.println("Two chars"); System.out.println((int) newline.charAt(0)); System.out.println((int) newline.charAt(1)); } else if (newline.length() == 1) { System.out.println("One char"); System.out.println((int) newline.charAt(0)); } } }Two chars 13 10
This example uses the Character.LINE_SEPARATOR
as a line break. This inserts the character "\r" in between the two strings.
LINE_SEPARATOR
value to add it to a string
. Otherwise it is displayed as an integer.public class Program { public static void main(String[] args) { // ... Use Character value. // The cast is important. String result = "one" + (char) Character.LINE_SEPARATOR + "two"; System.out.println(result); } }one two
LINE_SEPARATOR
valueHere I show that the LINE_SEPARATOR
constant is equal to the value 13, which is the value "\r." This is not a "\n" value.
public class Program { public static void main(String[] args) { // The LINE_SEPARATOR equals the \r char. System.out.println((int) Character.LINE_SEPARATOR); System.out.println((int) '\r'); } }13 13
This program directly uses the "\n" character to create a line break. This is a clear approach to the problem. It can also be optimized into a single literal by a compiler.
public class Program { public static void main(String[] args) { // ... Use concat with newline string. String result = "bird" + "\n" + "fish"; System.out.println(result); } }bird fish
BufferedWriter
, newLine
When writing a text file with BufferedWriter
, we can use the newline method. This inserts the line-break
into the output text.
We added newlines to strings with concatenation. We use System.lineSeparator
, a Character constant, and the newline literal.
For the lineSeparator
method, we get a two-char
string
on Windows systems. This is longer than a "\n" character. For the shortest and simplest line breaks, use a "\n" char
.