Since the new line separator varies from platform to platform (e.g. \\n on Unix-like systems or \\r\\n on Windows) it is often necessary to have a platform-independent way of accessing it. In Java it can be retrieved from a system property:

System.getProperty("line.separator")

Because the new line separator is so commonly needed, from Java 7 on a shortcut method returning exactly the same result as the code above is available:

System.lineSeparator()

Note: Since it is very unlikely that the new line separator changes during the program’s execution, it is a good idea to store it in in a static final variable instead of retrieving it from the system property every time it is needed.

When using String.format, use %n rather than \\n or ‘\r\n’ to output a platform independent new line separator.

System.out.println(String.format('line 1: %s.%nline 2: %s%n', lines[0],lines[1]));