Java String new line
Solution 1:
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
Solution 2:
You can also use System.lineSeparator()
:
String x = "Hello," + System.lineSeparator() + "there";
Solution 3:
Example
System.out.printf("I %n am %n a %n boy");
Output
I
am
a
boy
Explanation
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
.
Solution 4:
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");