Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between %n and \n for printing a new line in Java [duplicate]

Tags:

java

The documentation of Java specifies to use %n rather than \n for a newline.

As per the Oracle JavaSE Number documentation

A new line character appropriate to the platform running the application. You should always use %n, rather than \n.

What is the prominent difference between both if any?.

like image 278
Ashish Krishnan Avatar asked Aug 13 '15 06:08

Ashish Krishnan


2 Answers

%n is portable between various platforms, the value emitted from %n will suit the underlying platform, whereas value emitted by \n is same for all the platforms.

\n is the correct newline character for Unix-based systems, other systems may use different characters to represent the end of a line.

Windows system use \r\n, and early MacOS systems used \r.

like image 133
Abimaran Kugathasan Avatar answered Sep 19 '22 17:09

Abimaran Kugathasan


%n is special code (placeholder) for new-line symbol (that might be \r\n or \n) in formatted string and \n is an actual symbol.

You can think of %n as a symbol that will be replaced with the \r\n or \n in the resulting string.

like image 42
Developer Marius Žilėnas Avatar answered Sep 18 '22 17:09

Developer Marius Žilėnas