In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
What does \n mean in Java? This means to insert a new line at this specific point in the text. In the below example, "\n" is used inside the print statement, which indicates that the control is passed to the next line. As a result, the text following "\n" will be printed on the next line.
in a string prevents actually making a new line and instead of Type (new line) for a new line it is Type \n for a new line .
Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .
System.out.println("I\nam\na\nboy");
System.out.println("I am a boy".replaceAll("\\s+","\n"));
System.out.println("I am a boy".replaceAll("\\s+",System.getProperty("line.separator"))); // portable way
You can also use System.lineSeparator()
:
String x = "Hello," + System.lineSeparator() + "there";
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
.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With