0

We all read something like this:

use the System.getProperty(String) method to refer to items which depend on the system, such as line terminators and path separators.

The quote is copied from this web site.

I hard-coded an \n, and the code below works on my Windows machine as expected.

package sample;

public class Main {

    public static void main(String[] args) {
        System.out.println("hello\nworld");
    };

}

The output is:

hello
world

I thought the Java compiler replaced \n with \r\n silently. So I downloaded JD GUI, opened the JAR file, and saw Hello\nworld. Can anybody give me an example where \n doesn't work and System.getProperty("line.separator") does?

Maksim Dmitriev
  • 5,985
  • 12
  • 73
  • 138
  • 1
    Write your Sting into a file with the Java program, open it with Notepad and you will see what the Problem is – Jens May 09 '17 at 08:41
  • @Jens, you're right. It looks like Command Prompt substitutes the correct line endings, and Notepad doesn't. So if you convert your comment to an answer, I'll accept it – Maksim Dmitriev May 09 '17 at 08:55

2 Answers2

0

There are different line separators, depends on the OS. Read this thread: What is the difference between \r and \n?

Excerpt of if:

More importantly, Unix tends to use \n as a line separator; Windows tends to use \r\n as a line separator and Macs (up to OS 9) used to use \r as the line separator. (Mac OS X is Unix-y, so uses \n instead; there may be some compatibility situations where \r is used instead though.)

Community
  • 1
  • 1
urgas9
  • 806
  • 9
  • 22
  • This is a possible duplicate question: http://stackoverflow.com/questions/36796136/difference-between-system-getpropertyline-separator-and-n – urgas9 May 09 '17 at 08:44
0

From the comment: It looks like Command Prompt substitutes the correct line endings, and Notepad doesn't.

Maksim Dmitriev
  • 5,985
  • 12
  • 73
  • 138