riggedCoinflip
riggedCoinflip

Reputation: 485

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?

Upvotes: 0

Views: 1162

Answers (2)

Huiagan
Huiagan

Reputation: 61

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.

Upvotes: 3

Harshal Parekh
Harshal Parekh

Reputation: 6027

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

Upvotes: 2

Related Questions