Languages
[Edit]
EN

Java - how to get new line character for given platform eg Windows, Linux or MacOS - platform dependent?

14 points
Created by:
JustMike
3485

1. Overview:

In java it is possible to get platform dependent new line character in couple of ways:

  1. System.lineSeparator()
  2. System.getProperty("line.separator")
  3. String.format("%n")

2. New line character on most popular operating systems

Operating System Name New line character
Windows \r\n
Linux / Unix \n
MacOS \n

3. Java code example

public class Example {

    public static void main(String[] args) {

        String newLine1 = System.lineSeparator();
        String newLine2 = System.getProperty("line.separator");
        String newLine3 = String.format("%n");

        System.out.println(newLine1);
        System.out.println(newLine2);
        System.out.println(newLine3);
    }
}

When running on Windows:

Screenshot with 3 x ways in java how to get new line character - windows new character \r\n in intellij IDEA debugging session - https://dirask.com/q/8jme2j
Intellij IDEA debugging session - Windows new line \r\n

References

  1. Newline - wiki

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍