简体   繁体   中英

Why do we use \n rather than return key directly in java string?

We can use \n to stand for linefeed in string. But why we can't use return key directly?

String str1 = "\n";
//error
String str2 = "
";

I guess the reason for this limitation is that if I forget the right double quotation marks, compiler will not detect this error until end of file.

The reason you use \n instead of the return key directly as the return key is considered a "non-graphic" character in the world of Java (as well as an overwhelming majority of other programming languages). Characters like return, tabs, etc. can cause compiler and/or style issues when used in strings directly for most programing languages (like Java).

\n is an escape sequence that is a fill-in for these non-graphic characters. The reason these exist is it can reduce the readability of code to use non-graphic characters in Java strings.

You can read more about escape sequences for characters in Java here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM