Why can't I write ch=ch+1; instead of ch++; though they have same meaning

二次信任 提交于 2019-12-22 05:05:16

问题


package practicejava;

public class Query {

    public static void main(String[] args) {
        char ch = 66;
        System.out.println("character= " + ch);

        ch++;

        System.out.println("character = " + ch);

    }
}

Technically ch++; and ch=ch+1; are the same but why do I get an error when I write ch=ch+1; instead of ch++;?


回答1:


You need to provide a cast in order to do that :

ch = (char) (ch + 1);

This is because the expression ch + 1 is is promoted (upcast) to an int. In order for you to reassign this expression to a char you need to explicitly downcast it.




回答2:


By ch+1, the char ch will be promoted to int first, just like ((int)ch) + 1, so the result will be an int.

When you try assign an int(32 bit) back to a char(16 bit), it might loss accuracy, you need to do it explictly ch = (char)(ch + 1);


This is called Binary Numeric Promotion:

Binary numeric promotion is performed on the operands of certain operators:

...

The addition and subtraction operators for numeric types + and - (§15.18.2)

and it will perform

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.




回答3:


First of all, note that a char is 2 bytes large (16 bit), and an int is 32bit.

1. When typing ch++:

to apply the ++ operator, there is no type cast but the operator simply causes the bit represent of that char to increase by 1 to itself. Refer to JLS11 chapter 15.14.2,page 575:

The type of the postfix increment expression is the type of the variable.

2. When typing ch=ch+1:

ch is firstly casted to int, then it is added by 1(still an int), and the = is actually tring to cast the int which has 32bits into a char which has only 16 bits, note that this may lose accuracy. So without an explicitly cast, the compiler will complain about that, which is the cause of the error.



来源:https://stackoverflow.com/questions/53791297/why-cant-i-write-ch-ch1-instead-of-ch-though-they-have-same-meaning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!