I have string like
\"I am a boy\".
I want to print like this way
\"I
am
a
boy\".
Can anybody help me?<
\n
is used for making separate line;
Example:
System.out.print("I" +'\n'+ "am" +'\n'+ "boy");
Result:
I
am
boy
Platform-Independent Line Breaks
finalString = "physical" + System.lineSeparator() + "distancing";
System.out.println(finalString);
Output:
physical
distancing
Notes:
Java 6: System.getProperty("line.separator")
Java 7 & above: System.lineSeparator()
It can be done several ways. I am mentioning 2 simple ways.
Very simple way as below:
System.out.println("I\nam\na\nboy");
It can also be done with concatenation as below:
System.out.println("I" + '\n' + "am" + '\n' + "a" + '\n' + "boy");
System.out.printf("I %n am %n a %n boy");
I
am
a
boy
It's better to use %n
as an OS independent new-line character instead of \n
and it's easier than using System.lineSeparator()
Why to use %n
, because on each OS, new line refers to a different set of character(s);
Unix and modern Mac's : LF (\n)
Windows : CR LF (\r\n)
Older Macintosh Systems : CR (\r)
LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n
is OS agnostic, it is portable. It stands for \n
on Unix systems or \r\n
on Windows systems and so on. Thus, Do not use \n
, instead use %n
.
Here it is!! NewLine is known as CRLF(Carriage Return and Line Feed).
Sample:
System.out.println("I\r\nam\r\na\r\nboy");
Result:
It worked for me.