8

你能解释一下最后 2 个打印语句的内容吗?那就是我迷路的地方。

public class Something
{
    public static void main(String[] args){
        char whatever = '\u0041';

        System.out.println( '\u0041'); //prints A as expected

        System.out.println(++whatever); //prints B as expected

        System.out.println('\u0041' + 1); //prints 66 I understand the unicode of 1     adds up the 
        //unicode representing 66 but why am I even returning an integer when in the previous statement I returned a char?

        System.out.println('\u0041' + 'A'); //prints 130 I just wanted to show that adding an 
        //integer to the unicode in the previous print statement is not implicit casting because 
        //here I add a char which does not implicitly cast char on the returned value

    }
}
4

3 回答 3

8

这是因为二进制数字提升

当运算符将二进制数值提升应用于一对操作数时,每个操作数都必须表示一个可转换为数值类型的值,以下规则按顺序应用,使用扩展转换(第 5.1.2 节)在必要时转换操作数:

  • 如果任何操作数是引用类型,则执行拆箱转换(第 5.1.8 节)。然后:
  • 如果任一操作数是 double 类型,则另一个操作数将转换为 double。
  • 否则,如果任一操作数的类型为浮点型,则另一个将转换为浮点型。
  • 否则,如果任一操作数是 long 类型,则另一个将转换为 long。
  • 否则,两个操作数都转换为 int 类型。

基本上,两个操作数都转换为 a int,然后System.out.println(int foo)调用 the 。+,*等可以返回的唯一类型是double, float, long, 和int

于 2013-04-05T04:50:51.700 回答
2

'\u0041' + 1产生int,您需要将其强制转换为,char以便 javac 将调用绑定到println(char) 而不是prinln(int)

System.out.println((char)('\u0041' + 1)); 
于 2013-04-05T04:49:46.987 回答
0

whatever是一个字符,并且++whatever意味着whatever = whatever + 1(忽略前缀顺序)

由于涉及到赋值,结果被转换为 char,所以调用了 char 方法。但是在第 3-4 次打印中,没有赋值,并且按照规则,所有求和运算默认发生在 int 中。所以在 print 操作之前,它对 and 求和char + charchar+int由于没有反向赋值,所以在操作之后它仍然是 int,所以调用了 integer 方法。

于 2013-04-05T04:57:43.927 回答