C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Concat: We combine the two strings "cat" and "dog" with a lineSeparator() call in between. This composes the strings into two lines.
Java program that uses System.lineSeparator
public class Program {
public static void main(String[] args) {
// ... Use System.lineSeparator.
String result = "cat" + System.lineSeparator() + "dog";
System.out.println(result);
}
}
Output
cat
dog
And: On a UNIX-based system like Mac or Linux, the program should instead display "One char."
Java program that shows value of System.lineSeparator
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));
}
}
}
Output
Two chars
13
10
Warning: It is probably better and more standard to use the constant "\n" for a line break.
Cast: We must cast the LINE_SEPARATOR value to add it to a string. Otherwise it is displayed as an integer.
Java program that uses Character.LINE_SEPARATOR
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);
}
}
Output
one
two
Java program that shows LINE_SEPARATOR 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');
}
}
Output
13
13
Java program that uses newline literal
public class Program {
public static void main(String[] args) {
// ... Use concat with newline string.
String result = "bird" + "\n" + "fish";
System.out.println(result);
}
}
Output
bird
fish