美文网首页
Java“中文”编程

Java“中文”编程

作者: lemonTreeTop | 来源:发表于2016-12-08 23:34 被阅读127次

    Java是国际化的编程语言,印象中看到可以用任何语言做标识符,于是验证一下,然后动手试了一下

    class 输出类{
         public static void main(String[] args) {
            String 字符串变量1="你好,JAVA-1\n";
            System.out.printf(字符串变量1);
            输出方法();
        }
        private static void 输出方法(){
            String 字符串变量2="你好,JAVA-2";
            System.out.printf(字符串变量2);
        }
    }
    

    编译执行结果

    result.png

    为什么可以java支持中文作为标识符呢?
    书上都是这样子写的:

    • 标识符由字母、数字、下划线“_”、美元符号“$”组成,第一个字符不能是数字
    • 不能把java关键字作为标识符
    • 标识符没有长度限制
    • 标识符对大小写敏感

    但是这样子明显和测试的结果不一致,标识符是中文也可以,不一定是字母,那么我就去翻一下官网java教程说明http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8

    3.8. Identifiers
    An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.

    Identifier:
    IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral

    IdentifierChars:
    JavaLetter {JavaLetterOrDigit}

    JavaLetter:
    any Unicode character that is a "Java letter"(//使用的Unicode字符集)

    JavaLetterOrDigit:
    any Unicode character that is a "Java letter-or-digit"

    "Java letter" is a character for which the method Character.isJavaIdentifierStart(int) returns true.

    "Java letter-or-digit" is a character for which the method Character.isJavaIdentifierPart(int)
    returns true.

    The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z(\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).

    Letters and digits may be drawn from the entire Unicode character set, which supports most writing scripts in use in the world today, including the large sets for Chinese(//中文), Japanese, and Korean. This allows programmers to use identifiers in their programs that are written in their native languages.(//重点在这里)

    An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

    以上简略翻译一下官网文档说明。内容都是简单的,只翻译了重点。 不知道以前的java规定是字母,还是翻译教学有误。我觉得翻译应该是加引号的‘‘Java 字母’’,而不是字母。现在官网的教程说明已经很清楚了,但是我们的教材还没更新,本身学习就具有滞后性,再加上教材的滞后性,这样显得更加滞后了。

    那有人也会说,用中文作标识符不好,如知乎的这个问题,那再教你可以用中文作标识符有什么意义呢?

    中文本身不太适合做编程,标识符使用英文才能更好地标识。尝试用中文去作标识符的意义在于深刻认识标识符是什么,Unicode是什么,编码是什么,而不是书说是什么就是什么。

    相关文章

      网友评论

          本文标题:Java“中文”编程

          本文链接:https://www.haomeiwen.com/subject/kbasmttx.html