Error due to content in a legal Comment in Java

2019-01-29 02:05发布

问题:

On this coderanch link, I found that the following comment will give compiler error :-

// Compiler Error due to this Unicode char '\u000a'

Reason being, the Unicode sequence is directly replaced by the actual character it corresponds to. Since '\u000a' corresponds to newLine character, a newLine is placed at the place where '\u000a' is found.

My question is that, "Is there any other way of having Compilation Error due to a comment?"

回答1:

IF you define a function a deprecated in a comment (@deprecated), AND you set your compiler to throw errors when deprecated methods are used (at least the internal Eclipse compiler can be configured this was, AFAIK)



回答2:

"The compiler not only translates Unicode escapes into the characters they represent before it parses a program into tokens [...], but it does so before discarding comments and white space [JLS 3.2]." Java™ Puzzlers: Traps, Pitfalls, and Corner Cases By Joshua Bloch, Neal Gafter.

And the next lines are valid Java code:

\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020
\u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079
\u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020
\u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063
\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028
\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020
\u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b
\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074
\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020
\u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b
\u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d


回答3:

/* Compiler Error due to this Unicode char '*/' */


回答4:

This error is not caused by the comment itself. If you use the same \u000a somewhere else in your code, you'll get the same kind of error. For example:

// This will give you a similar error
char c = '\u000a';

The fact that the escape sequence is in a comment in your example doesn't mean that the comment is what causes the error.