Skip to main content

I often use „`StringBuilder„` and „`StringBuffer„` in Java and I also have to include newlines in the Strings I generate.
Up to date I always created a „` private static final String newline = „n“;„` and used it wherever I needed a newline.

Today I thought about this practice I used for so long now and asked myself if this is really needed – of course it was not…
The better way to do it, is to use „`System.getProperty(„line.separator“)„`. From Java 7 onwards you can also use „`System.lineSeparator();„`

But why is the new approach better? Because the „`System„` class now correctly handles newlines on different OS. It technically won´t make any impact if you run the software only on Unix systems but if you switch to Windows you will see the difference 😉

Daniel Sachse

Author Daniel Sachse

More posts by Daniel Sachse