Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print \n in a String in java [duplicate]

Tags:

java

I want to print \n.

String text = "";

text = "\n is used for new line";

but the \n is not showing when I run the code. How to do this?

like image 662
Saeed ur Rehman Avatar asked Nov 15 '15 20:11

Saeed ur Rehman


People also ask

What does \n do in a string?

Adding Newline Characters in a String. Operating systems have special characters denoting the start of a new line. For example, in Linux a new line is denoted by “\n”, also called a Line Feed. In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF.

What does \n in Java do?

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.


2 Answers

Escape the \ with \

text = "\\n is used for new line";
like image 179
rajuGT Avatar answered Oct 19 '22 07:10

rajuGT


If you want to actually write the two chars \and n to output, you need to escape the backslash: \\n.

All escape sequences are listed in the documentation: https://docs.oracle.com/javase/tutorial/java/data/characters.html

like image 6
Kvam Avatar answered Oct 19 '22 05:10

Kvam