This post will explore how to print newline in Java.

A newline (aka end of the line (EOL), line feed, or line break) signifies the end of a line and the start of a new one. Different operating systems use different notations for representing a newline using one or two control characters. On Unix/Linux and macOS systems, newline is represented by "\n"; on Microsoft Windows systems by "\r\n"; and on classic Mac OS with "\r".

1. Using platform-dependent newline character

The commonly used solution is to use platform-dependent newline characters. For instance, "\n" on Unix and "\r\n" on Windows OS. The problem with this solution is that your program will not be portable.

Download  Run Code

2. Using System.getProperty() method

The recommended solution is to use the value of the system property line.separator, which returns the system-dependent line separator string. Since its value depends on the underlying OS, your code will be portable (platform-independent).

Download  Run Code

3. Using System.lineSeparator() method

Another solution is to use the built-in line separator lineSeparator() provided by the System class. It simply returns the value of the system property line.separator.

Download  Run Code

4. Using %n newline character

Another plausible way of getting the platform’s preferred line separator is to use the platform-independent newline character %n with the printf() method.

Download  Run Code

5. Using System.out.println() method

If we need a newline at the end of the string, we should call the println() method, which outputs a newline character appropriate to your platform.

Download  Run Code

That’s all about printing newline in Java.