简体   繁体   中英

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

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++; ?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM