Javatpoint Logo
Javatpoint Logo

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.

NewLine1.java

Output:

Hello
World

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).

NewLine2.java

Output:

Hello
World

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.

NewLine3.java

Output:

Hello
World

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.

NewLine4.java

Output:

Hello
World

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.

NewLine5.java

Output:

Hello
World

In this article, we have discussed different ways to add a new line in a Java program.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA