New Line 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".
Methods to Print New Line in Java
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.
2. Using getProperty()Method
The recommended solution is to use the value of the system property line.separator. It returns the system-dependent line separator string. Since its value depends on the underlying OS, your code will be portable (platform-independent).
3. Using lineSeparator()Method
Another solution is to use the built-in line separator method lineSeparator(). It belongs to the System class. It simply returns the value of the system property line.separator.
4. Using %nnewline Character
Another reasonable way of getting the platform's preferred line separator is to use the platform-independent newline character %n with the printf() method.
5. Using out.println()Method
If we need a newline at the end of the string, we should call the println() method, that outputs a newline character appropriate to your platform.
In this article, we have discussed different ways to add a new line in a Java program.
Next TopicReturn Statement in Java