Adding new line in printf() or format() - java

today I was reading in the java Tutorials docs from Oracle about Formatting Numeric Print Output and I encountered println() vs printf() vs format() after I understood the differences I read the following sentence which makes no sense for me.
A new line character appropriate to the platform running the application. You should always use %n, rather than \n.
so the main question of this is why "should" I always use %n instead of \n what difference does this make?

The %n is like a placeholder for whatever the newline character may be for a particular system. %n could very well be \n for a specific system or \r\n for another such as the case with windows. Using %n is the safer alternative to typing \n because as #user85421 commented, some windows applications don't recognize \n.

Related

Does Java MessageFormat have a platform lineseparator like String.format does?

This is a long shot, but I'm hoping to replace the newline literals in MessageFormat code like
LOG.log(INFO, "message={0}\nAnd extra blank line\n", new String[]{message});
with a platform-independent pattern. The String.format() pattern %n does not work for Logger or MessageFormat. I'd like to avoid passing System.lineseperator as an argument like this:
LOG.log(INFO, "message={0}{1}And a blank line{1}",new String[]{message, System.lineSeparator()});
I don't see any mention of newline or lineseparator in the docs for MessageFormat, but perhaps it is mentioned somewhere else.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/MessageFormat.html
Does Java MessageFormat have a platform lineseparator like String.format does?
According to my reading of the code, the answer is No.
And there aren't any extant RFEs or Bug reports about this that I can see in the Java or OpenJDK Bug trackers1.
However, as Joop notes, since you are actually asking this in the context of logging, there are a few other ways to solve this (though not all will be practical):
Ignore the problem. These messages are going into log files. Maybe it doesn't really matter that the line separators in messages in the log files don't always match the platform.
Create a custom subclass of MessageFormat that recognizes a syntax that means "platform specific line separator".
Handle the line separators by translating them in a custom log message appender or formatter; e.g.
Translate all line separators of the "wrong kind".
Recognize and translate a magic character sequence ...
Change to a different logging framework that uses java.util.Formatter for message construction. AFAIK, most modern frameworks do.
Submit an RFE.
1 - You could read that as "evidence" of how little use there is of MessageFormat in real world / modern applications, or how few people use it in contexts where line separators matter.
#Bohemian commented:
Why do you want to avoid "passing System.lineseparator as an argument"?
I would have thought that was self-evident. It is clunky.

Using %n as new line

as recommended as for example in this post:
https://stackoverflow.com/a/38077906/12340711
It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()
However, the function does not work for me:
\n:
System.out.println("foo\nbar");
>>>foo
>>>bar
works as it should.
%n:
System.out.println("foo%nbar");
>>>foo%nbar
is not interpreted.
Can somebody explain me why %n does not work for me? Is it perhaps not longer supported or am I missing something?
Java provides you the System.lineSeparator() constant. That will break the line in a OS independent way if you are using println. You can also just use \n in a string to break the line if you are just playing around with code. It's easy and fast. Note that println just prints a pure text to the console.
When you use printf, you will actually be using a java.util.Formatter to format the string before the console output. All details of the java.util.Formatter can be found at (Java 8 docs link): https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
So, if you want to format a string using println, you will need to format it first using java.util.Formatter with something like:
String formattedStr = String.format("%s = %d %n hello", "joe", 35);
System.out.println(formattedStr);
Where %s is a string, %d is a integer number and %n a line break (described in documentation link above).
printf is just a shortcut to the above 2 lines of code where the String.format is already inside printf implementation.
System.out.printf("%s = %d %n hello", "joe", 35);
And you can also use \n in a printf string:
System.out.printf("%s = %d \n hello", "joe", 35);
Finally, it is important for you to understand that in a real world project you should always use System.lineSeparator() instead \n if you are not using a java.util.Formatter (in a Formatter, use %n). Also, you should never use System.out.* for real projects. Use a logging framework instead.
%n is interpreted as String by System.out.println().
To use %n, you must use System.out.printf(), like in the example you have posted.
Note: \n is interpreted as newline by System.out.printf().

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

This question already has answers here:
What's up with Java's "%n" in printf?
(8 answers)
Closed 7 years ago.
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?.
%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.
%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.

printf: Difference between \n and %n [duplicate]

I'm reading Effective Java and it uses %n for the newline character everywhere. I have used \n rather successfully for newline in Java programs.
Which is the 'correct' one? What's wrong with \n ? Why did Java change this C convention?
From a quick google:
There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas"\n" is not.
Please refer
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Original source
%n is portable across platforms
\n is not.
See the formatting string syntax in the reference documentation:
'n' line separator The result is the
platform-specific line separator
While \n is the correct newline character for Unix-based systems, other systems may use different characters to represent the end of a line. In particular, Windows system use \r\n, and early MacOS systems used \r.
By using %n in your format string, you tell Java to use the value returned by System.getProperty("line.separator"), which is the line separator for the current system.
Warning:
If you're doing NETWORKING code, you might prefer the certainty of \n, as opposed to %n which may send different characters across the network, depending upon what platform it's running on.
"correct" depends on what exactly it is you are trying to do.
\n will always give you a "unix style" line ending.
\r\n will always give you a "dos style" line ending.
%n will give you the line ending for the platform you are running on
C handles this differently. You can choose to open a file in either "text" or "binary" mode. If you open the file in binary mode \n will give you a "unix style" line ending and "\r\n" will give you a "dos style" line ending. If you open the file in "text" mode on a dos/windows system then when you write \n the file handling code converts it to \r\n. So by opening a file in text mode and using \n you get the platform specific line ending.
I can see why the designers of java didn't want to replicate C's hacky ideas regarding "text" and "binary" file modes.
Notice these answers are only true when using System.out.printf() or System.out.format() or the Formatter object. If you use %n in System.out.println(), it will simply produce a %n, not a newline.
In java, \n always generate \u000A linefeed character. To get correct line separator for particular platform use %n.
So use \n when you are sure that you need \u000A linefeed character, for example in networking.
In all other situations use %n
%n format specifier is a line separator that's portable across operating systems. However, it cannot be used as an argument to System.out.print or System.out.println functions.
It is always recommended to use this new version of line separator above \n.

What's up with Java's "%n" in printf?

I'm reading Effective Java and it uses %n for the newline character everywhere. I have used \n rather successfully for newline in Java programs.
Which is the 'correct' one? What's wrong with \n ? Why did Java change this C convention?
From a quick google:
There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas"\n" is not.
Please refer
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Original source
%n is portable across platforms
\n is not.
See the formatting string syntax in the reference documentation:
'n' line separator The result is the
platform-specific line separator
While \n is the correct newline character for Unix-based systems, other systems may use different characters to represent the end of a line. In particular, Windows system use \r\n, and early MacOS systems used \r.
By using %n in your format string, you tell Java to use the value returned by System.getProperty("line.separator"), which is the line separator for the current system.
Warning:
If you're doing NETWORKING code, you might prefer the certainty of \n, as opposed to %n which may send different characters across the network, depending upon what platform it's running on.
"correct" depends on what exactly it is you are trying to do.
\n will always give you a "unix style" line ending.
\r\n will always give you a "dos style" line ending.
%n will give you the line ending for the platform you are running on
C handles this differently. You can choose to open a file in either "text" or "binary" mode. If you open the file in binary mode \n will give you a "unix style" line ending and "\r\n" will give you a "dos style" line ending. If you open the file in "text" mode on a dos/windows system then when you write \n the file handling code converts it to \r\n. So by opening a file in text mode and using \n you get the platform specific line ending.
I can see why the designers of java didn't want to replicate C's hacky ideas regarding "text" and "binary" file modes.
Notice these answers are only true when using System.out.printf() or System.out.format() or the Formatter object. If you use %n in System.out.println(), it will simply produce a %n, not a newline.
In java, \n always generate \u000A linefeed character. To get correct line separator for particular platform use %n.
So use \n when you are sure that you need \u000A linefeed character, for example in networking.
In all other situations use %n
%n format specifier is a line separator that's portable across operating systems. However, it cannot be used as an argument to System.out.print or System.out.println functions.
It is always recommended to use this new version of line separator above \n.

Categories