short s=1;
s=s+1;与s+=1;有什么区别,s+=1内部是怎样运算的,还有s+=1为什么不需要转型,各位高手麻烦了!

解决方案 »

  1.   

    s+=1;相当于s = (short)(s+1);编译器会添加强制转换操作。
    s=s+1; s+1得到的是int类型的结果,int赋给short变量s,不合法,编译错误。
      

  2.   

    看《java语言规范》,这是规定
    += 这样的表达式,需要的情况下自动进行强制转换。
    http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2
    15.26.2 Compound Assignment Operators
    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. 
    For example, the following code is correct:short x = 3;
    x += 4.6;and results in x having the value 7 because it is equivalent to:
    short x = 3;
    x = (short)(x + 4.6);