Using %n as new line - java

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().

Related

Adding new line in printf() or format()

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.

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.

How to create a String with carriage returns?

For a JUnit test I need a String which consists of multiple lines. But all I get is a single lined String. I tried the following:
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
I also tried \n\r instead of \n. System.getProperty("line.separator") doesn't work too. it produces a \n in String and no carriage return. So how can I solve that?
It depends on what you mean by "multiple lines". Different operating systems use different line separators.
In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.
But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.
The fastest way I know to generate a new-line character in Java is: String.format("%n")
Of course you can put whatever you want around the %n like:
String.format("line1%nline2")
Or even if you have a lot of lines:
String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")
Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.
Do this:
Step 1: Your String
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
Step 2: Just replace all "\n" with "%n" the result looks like this
String str = ";;;;;;%n" +
"Name, number, address;;;;;;%n" +
"01.01.12-16.02.12;;;;;;%n" +
";;;;;;%n" +
";;;;;;";
Notice I've just put "%n" in place of "\n"
Step 3: Now simply call format()
str=String.format(str);
That's all you have to do.
Try append characters .append('\r').append('\n'); instead of String .append("\\r\\n");
Thanks for your answers. I missed that my data is stored in a List<String> which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.

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