This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?

(8个答案)


5年前关闭。





我遇到了Java打印字符为ASCII的情况。如果我们尝试打印两个字符,则其将打印ASCII值的总和。

System.out.println('c'); =>> c
System.out.println('a'+'b'); =>> 195 (97+98)


只想知道为什么在第二种情况下它会打印那里的ASCII值的总和

最佳答案

在后台,编译器的行为太聪明了,用一个int常量值替换了char + char

在第一种情况下,调用println(char),在第二种情况下,调用println(int)

样例代码:

public static void main(String[] args) {
    System.out.println('a');
    System.out.println('a' + 'b'); // the compiler first "resolves" the expression 'a'+'b' (since char cannot be added they are added as ints) and then tries to call the correct `println(int)` method.
}


字节码:

public static void main(java.lang.String[]);
   descriptor: ([Ljava/lang/String;)V
   flags: ACC_PUBLIC, ACC_STATIC
   Code:
     stack=2, locals=1, args_size=1
        0: getstatic     #16                 // Field java/lang/System.out:Ljav
/io/PrintStream;
        3: bipush        97                 // for single char. (pushed a byte as an int)
        5: invokevirtual #22                 // Method java/io/PrintStream.prin
ln:(C)V
        8: getstatic     #16                 // Field java/lang/System.out:Ljav
/io/PrintStream;
       11: sipush        195                // push sum of 2 chars as a short
       14: invokevirtual #28                 // Method java/io/PrintStream.prin
ln:(I)V
       17: return

10-07 19:09
查看更多