Unicode decoding takes place before any other lexical translation. The key benefit of this is that it makes it trivial to go back and forth between ASCII and any other encoding. You don't even need to figure out where comments begin and end!
As stated in JLS Section 3.3 this allows any ASCII based tool to process the source files:
[...] The Java programming language specifies a standard way of transforming a program written in Unicode into ASCII that changes a program into a form that can be processed by ASCII-based tools. [...]
This gives a fundamental guarantee for platform independence (independence of supported character sets) which has always been a key goal for the Java platform.
Being able to write any Unicode character anywhere in the file is a neat feature, and especially important in comments, when documenting code in non-latin languages. The fact that it can interfere with the semantics in such subtle ways is just an (unfortunate) side-effect.
There are many gotchas on this theme and Java Puzzlers by Joshua Bloch and Neal Gafter included the following variant:
Is this a legal Java program? If so, what does it print?
(This program turns out to be a plain "Hello World" program.)
In the solution to the puzzler, they point out the following:
More seriously, this puzzle serves to reinforce the lessons of the previous three: Unicode escapes are essential when you need to insert characters that can’t be represented in any other way into your program. Avoid them in all other cases.
- answered 3 years ago
- Sunny Solu