Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between \n and System.lineSeparator();? [duplicate]

Tags:

java

My Professor kept telling us that she wants us to use the System.lineSeparator(); to create an empty new line, she didn't specify any reasons, but basically said it was cleaner. What's the difference and should I use it in the described manner over.

System.out.println("[your message]\n")

in contrast to

System.out.println("[your message]");
System.lineSeparator();
like image 371
blkpingu Avatar asked Mar 17 '18 18:03

blkpingu


3 Answers

The \n character is a single character which is called "new line", usually. Sometimes it may be called "linefeed" to be more accurate. The line separator varies from computer to computer, from Operating System to Operating System. You will get different line separators on Windows and Unix.

If you run this: System.getProperty("line.separator") it will return the line separator that is specific to your OS. On windows it will return \r\n and on Unix it will return \n.

I hope that it will be clear enough for you.

like image 63
Dina Bogdan Avatar answered Oct 01 '22 22:10

Dina Bogdan


My Professor kept telling us she want us to use the System.lineSeparator(); to create an emphty new line

Are you actually sure she said that? Because invoking System.lineSeparator(); does nothing: it returns a string, which is simply discarded.

If you want to insert a new line (in System.out), use:

System.out.println();
like image 23
Andy Turner Avatar answered Oct 01 '22 22:10

Andy Turner


Here's what the API documentation has to say about System.lineSeparator:

Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator.

On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".

like image 41
Chris Martin Avatar answered Oct 01 '22 22:10

Chris Martin