Print newline in Java
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.
|
1 2 3 4 5 6 |
class Main { public static void main(String[] args) { System.out.println("Hello" + '\n' + "World"); } } |
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).
|
1 2 3 4 5 6 7 8 |
class Main { public static void main(String[] args) { String newline = System.getProperty("line.separator"); System.out.println("Hello" + newline + "World"); } } |
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.
|
1 2 3 4 5 6 7 8 |
class Main { public static void main(String[] args) { String newline = System.lineSeparator(); System.out.println("Hello" + newline + "World"); } } |
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.
|
1 2 3 4 5 6 |
class Main { public static void main(String[] args) { System.out.printf("Hello%nWorld"); } } |
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.
|
1 2 3 4 5 6 7 8 |
class Main { public static void main(String[] args) { System.out.println("Hello"); System.out.println("World"); } } |
That’s all about printing newline in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)