Java Unicode 翻译

标签 java unicode

我遇到了以下代码:

public class LinePrinter {
    public static void main(String args[]) {
      //Note: \u000A is unicode for Line Feed
      char c=0x000A;
      System.out.println(c);
    }
}

由于已完成 Unicode 替换,因此无法编译。

问题是,为什么注释 (//) 不覆盖编译器完成的 Unicode 替换?我认为编译器应该先忽略注释,然后再对代码进行翻译。

编辑:

不知道上面说的够不够清楚。

我知道上面会发生什么以及为什么会出错。我的期望是编译器在对代码进行任何翻译之前应该忽略所有注释行。显然,这里不是这种情况。我期待这种行为的理由。

最佳答案

它在 Java Puzzlers #14 - 解释的摘录中:

The key to understanding this puzzle is that Java provides no special treatment for Unicode escapes within string literals. The compiler translates Unicode escapes into the characters they represent before it parses the program into tokens, such as strings literals [JLS 3.2].

JLS v7 中的相关段落是 paragraph 3.3 :

A compiler for the Java programming language ("Java compiler") first recognizes Unicode escapes in its input, translating the ASCII characters \u followed by four hexadecimal digits to the UTF-16 code unit (§3.1) of the indicated hexadecimal value, and passing all other characters unchanged.

JLS 第 3 节的介绍给出了为什么会出现这种情况的提示:

Programs are written in Unicode (§3.1), but lexical translations are provided (§3.2) so that Unicode escapes (§3.3) can be used to include any Unicode character using only ASCII characters.

关于Java Unicode 翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13761848/

相关文章:

python 将 unicode 转换为 "print"形式

unicode - 比较 Rebol 3 中的字符

java - maven 问题(Eclipse Juno)

java - 从 OAuth2.1 迁移到 OAuth2.0

java - 在 Ubuntu 上的处理 IDE (PDE) 中更改 "system"字体大小

java - 如何在 Liferay 中提取嵌套的 JSON 元素

java - 将已签名的 apk 从 android studio 部署到设备

python - 属性错误: 'unicode' object has no attribute 'remove'

c++ - 为什么这个简单的程序不起作用?

java - Apache Poi - 将外文字符写入 Excel 97/2003(即中文、日文等)