Why doesn't a character increment in System.out.println()?

后端 未结 4 1796
轮回少年
轮回少年 2020-12-22 14:00
char char1 = \'a\';   
System.out.println(char1);      //prints char 1
System.out.println(char1+1);    //prints char 1
System.out.println(char1++);     //prints char         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-22 14:23

    First, I'm assuming that because you say the increment in System.out.println works, that you have really specified:

    char char1 = 'a';
    

    EDIT

    In response to the change of the question (char1+1; => char1 += 1;) I see the issue. The output is

    a
    98
    b
    

    The 98 shows up because the char a was promoted to an int (binary numeric promotion) to add 1. So a becomes 97 (the ASCII value for 'a') and 98 results.

    However, char1 += 1; or char1++ doesn't perform binary numeric promotion, so it works as expected.

    Quoting the JLS, Section 5.6.2, "Binary Numeric Promotion":

    Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    If either operand is of type double, the other is converted to double.

    Otherwise, if either operand is of type float, the other is converted to float.

    Otherwise, if either operand is of type long, the other is converted to long.

    Otherwise, both operands are converted to type int.

    (emphasis mine)

提交回复
热议问题