Type mismatch: cannot convert from long to int

前端 未结 2 686
离开以前
离开以前 2021-01-20 22:06

I had the following lines of code

long longnum = 555L;
int intnum = 5;
intnum+=longnum;
intnum= intnum+longnum; //Type mismatch: cannot convert from long to          


        
2条回答
  •  感情败类
    2021-01-20 23:01

    That's because the compound assignment operator does implicit casting.

    From JLS Compound Assignment Operator:

    A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

    While in case of binary + operator, you have to do casting explicitly. Make your 4th assignment:

    intnum = (int)(intnum+longnum);
    

    and it would work. This is what your compound assignment expression is evaluated to.

提交回复
热议问题