How can I print a string adding newlines in Java?
When you want to add newlines to a string in Java, you can use String.join(System.lineSeparator(), "Line1", "Line2", "Line3");
which is a platform-independent way. Alternatively, you can use \n
for Unix-like systems or \r\n
for Windows:
Outputs:
Line1
Line2
Line3
Right tool for formatted output: String.format
When you want to be more precise with your formatted strings or need multiline output, String.format
is your friend. It is capable of including platform-specific newline characters %n
:
Mastering space-to-newline conversion
In some cases, we might want to split a phrase into multiple lines, treating spaces as newline indicators. That's when String.replaceAll
comes into play:
Print words line by line: System.out.println
Should you need to print each word or phrase on its own line, you can’t go wrong with System.out.println
:
Get right with every OS: Platform-Specific Newlines
Different Operating Systems interpret newlines differently. So, in order to have consistent output across platforms, the general rules are:
\n
for Unix/Linux/MacOS\r\n
for Windows
For cross-platform applications, the golden rule is: System.lineSeparator()
.
Joining Strings with Newlines
Another way to achieve the goal is by constructing a multi-line string through string concatenation with newlines:
Was this article helpful?