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.