In many situations you may need to use platform-dependent newline character in Java. There are several ways you can get that value, depending on the Java version you are using.

System properties

Java system properties always includes line.separator property which contains platform-dependent line separator (\n on UNIX and \r\n on Microsoft Windows). You can get that value using System.getProperty() method e.g.

final String newline = System.getProperty("line.separator");

Note that this method can be used with any Java version.

If you are using Java 1.7 or later, you can use dedicated method returning platform-dependent newline value: System.lineSeparator():

final String newline = System.lineSeparator();

Full set of always included properties can be found at System.getProperties() Javadoc page.

String formatting

In addition to the system property of dedicated method, you can use String.format (or other formatting methods) and %n token. As you can find on Format String Syntax, %n token is substituted with the platform-specific line separator in the output string e.g.

Linux

final String value = String.format("example%n"); // value = "example\n"

Windows

final String value = String.format("example%n"); // value = "example\r\n"

Note that this works only if you are using Java 1.5 or later.