Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

newline
java
communitycreator

How to get and use a new line character in Java

abhilash

What are newline characters?

A newline denotes the end of a line and the beginning of a new line. It is also known as the following:

  1. End of the Line (EOL)
  2. Line feed
  3. Line break

Different operating systems use different character notations to denote a newline, with one or two control characters.

Operating System End of Line Character
Windows \r\n
Linux \n
Mac \n

Platform dependent characters

We can use the control characters, \n in Unix and \r\n in Windows, as part of strings to denote the newline.

The problem with this approach would be the portability of the program.

Code

Example 1

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello" + "\n" + "Educative");
    }
}

line.separator property

The safest and recommended approach to use is the line.separator property using the System.getProperty() method in Java.

Example 2

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello" + System.getProperty("line.separator") + "Educative");
    }
}

System.lineSeparator() method

Another approach to use is the lineSeparator() static method of the System class.

Example 3

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello" + System.lineSeparator() + "Educative");
    }
}

RELATED TAGS

newline
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring