user5797668 user5797668 - 5 months ago 22
Java Question

Java - Print strings showing newline characters

I wish to print out strings to the console and it is important to see the exact string meaning that it should show the newline character

\n
in the logs. So it will be
"this is the exact sequence of chars \n"

Answer

You could replace all occurrences of the \n character with \\n (which will appear as \n when printed).

String str = "this is the exact sequence of chars \n";
System.out.print(str.replace("\n", "\\n");