Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 322
Tushar Mia Avatar asked Dec 15 '18 09:12

Tushar Mia


3 Answers

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.

like image 117
Nicholas Kurian Avatar answered Nov 13 '22 02:11

Nicholas Kurian


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.

like image 44
xingbin Avatar answered Nov 13 '22 03:11

xingbin


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.

like image 3
ZhaoGang Avatar answered Nov 13 '22 01:11

ZhaoGang