Explain Codes LogoExplain Codes Logo

How can I print a string adding newlines in Java?

java
formatted-strings
string-manipulation
newlines
Nikita BarsukovbyNikita Barsukov·Dec 24, 2024
TLDR

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:

String joinedLines = String.join(System.lineSeparator(), "Line1", "Line2", "Line3"); System.out.println(joinedLines); // Fast and easy way to newline heaven!

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:

String formatted = String.format("Line1%nLine2%nLine3"); System.out.println(formatted); // Beautifying lines, one format at a time!

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:

String singleLine = "Hello World Programming"; // yes it's a line but we want it to be a poem! String multipleLines = singleLine.replaceAll(" ", System.lineSeparator()); System.out.println(multipleLines); // Poetry in motion!

Should you need to print each word or phrase on its own line, you can’t go wrong with System.out.println:

String[] words = {"Hello", "World", "Programming"}; // Meet the rockstars! for(String word : words) { System.out.println(word); // Allowing our stars to shine, one line at a time! }

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:

String concatWithNewline = "Line1" + System.lineSeparator() + "Line2" + System.lineSeparator() + "Line3"; System.out.println(concatWithNewline); //Mission accomplished! Every line is a star!