The code is as follows:
public class Example014 {public static void main (string[] args) {/** * It's a test for \utest. *///\u0022 are double-quoted Unicode Escape character System.out.println ("a\u0022.length () + \u0022b". Length ());}}
Result Description:
The above program has compile errors. If you delete a multiline comment, the compilation error is eliminated and the output is 2.
Results Analysis:
The reason for the compilation error is analyzed first, and it is certain that the compilation error is caused by a multiline comment that contains a sequence of Unicode escape characters at the beginning of the \u, but does not immediately follow the 4 16-digit number (0~65535), which invalidates the escape. Java is a Unicode escape character that is allowed to start with \u in comments and in code, but requires that escaping be valid, or the compiler will report an error .
after deleting the comment or making the escape valid, the result of executing the above code is 2, and why? Originally,Java did not provide any special handling for Unicode escape characters in string literal constants. The compiler converts the Unicode escape characters into the characters they represent before parsing the program into various symbols . Therefore, the first Unicode escape character in the program will be the closing quotation mark for a single character string literal constant ("a"), and the second Unicode escape character will be the opening quotation mark for another one-character string literal constant ("B"), which actually runs the following code:
System.out.println ("a". Length () + "B". Length ());
in this way, it is no surprise that the output is 2.
(Note: This "Java doubts" series, are bloggers read "Java doubts" original book, the original book on the explanation and example part of the adaptation, and then write a blog post. All examples are tested in person and shared on GitHub. Use these examples to motivate yourself and benefit others. At the same time, all posts in this series will be posted in the blogger's personal public number (search for "Love Ape" or "ape_it") for easy reading. If there is any infringement of the original rights of the author's content, please inform the blogger in time, in order to promptly delete, if the reader has objection to the content of the text or questions, welcome to the Blog or public messages and other ways to discuss together. )
Source code Address: Https://github.com/rocwinger/java-disabuse
This article from "Winger" blog, declined reprint!
Use of the "Java doubts" Unicode escape character