Java string new line
In this article, we will take a look at various methods to line break between multiple strings or print each string from next line with example programs.
Each Operating system or platform has its own line separators or line break character which is
A.
\n
on Linux, Unix and Mac OS.B.
\r\n
on Windows
Adding these characters where a line break is required inserts or prints a new line. Example,
System.out.print("this is line1\n"); System.out.print("this is line2");
which prints
this is line1
this is line2
Method 2: Using System.lineSeparator()
Using line break characters for each OS or platform is not recommended. To print a new line, we need to check for current OS and add a line break with an if-else statement.
java.lang.System
class has a static lineSeparator()
method which returns the new line character according to the OS on which the application is currently running. Example,
String s = "line1" + System.lineSeparator() + "line2"; System.out.println(s);
This method was introduced in java 7.
Every JVM has a pre-defined property
line.separator
which returns the platform specific new line character. To get this property value, use System.getProperty()
method. Example,
String s = "line1" + System.getProperty("line.separator") + "line2"; System.out.println(s);
Remember that System.lineSeparator()
also invokes System.getProperty("line.separator")
internally.
Method 4: Using String.format()
String.format() formats the string values supplied to it according to the format and returns the formatted string.
It can be used to print a new line.
String.format()
accepts following arguments
1. format
A string which contains format characters such as %s
, %n
where %s
stands for string and %n
means a platform dependent new line character.
It may contain only format specifiers or a combination of string and format specifiers.
2. String values
Second argument is a var args. It can be 0 or any number of strings. These strings refer to the format specifiers that were provided as first argument.
Example code using String.format()
to print a new line is given below
// format specifiers for both strings System.out.println(String.format("%s%n%s", "First", "Second")); // format specifier for second string System.out.println(String.format("First%n%s", "Second")); // format specifier for first string System.out.println(String.format("%s%nSecond", "First"));
Note that %n
stands for new line.
All the above lines produce the same output
First
Second
Out of all the methods covered in this article, we must use System.lineSeparator()
to insert a new line or line break between strings. With this method, we need not write OS or platform dependent checks, JVM takes care of it.