short s1 = 1; 
s1=s1+1; //s1+1的结果是int型,把int型赋值给short型会报错
s1+=1;  //为什么s1+=1是正确的?

解决方案 »

  1.   

    Java 语言规范中讲到,复合赋值 E1 op= E2 等价于简单赋值E1 =
    (T)((E1)op(E2)),其中T 是E1 的类型,除非E1 只被计算一次。
    换句话说,复合赋值表达式自动地将它们所执行的计算的结果转型为其左侧变量
    的类型。
      

  2.   

    public class MyTest {
        public static void main(String args[]){
           short s1=32767;
           s1+=1;
           int i=32768;
           short s2=(short)i;
           System.out.println(s1);
           System.out.println(s2);
        }
    }
      

  3.   

    这是规范的原文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);
      

  4.   

    简单一点理解就是:
    x+=1   就是  x=x+1
    无论谁怎么调用这个+=
    都是调用等号左边的那个自己的值再加上右边的那个值,再回来赋值给它自己.
      

  5.   

    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);
      

  6.   

    short s1 = 1; 
    s1=s1+1; //s1+1的结果是int型,把int型赋值给short型会报错 
    s1+=1;  //为什么s1+=1是正确的?回答:
       s1 += 1 相当 s1 = (short)(s1+1),即默认加了强制类型转换,所以正确
      

  7.   

    所以表面看起来s1+=1;貌似很不错
    实际上无论使用,还是国际编码规范中,都推荐使用s1=s1+1
    一个为了清晰,另一个就是s1=s1+1如果类型不对会报错,可以帮助调整代码中变量的类型。
    所以变量类型的定义非常重要。
      

  8.   

    不要想复杂了丫,就是自加1.n=n+1,n+=1.
      

  9.   

    楼主没好好学习吧 老师讲过了 s1=s1+1  和  s1+=1  是一样的!这个也太基础了 ! 建议重新复习一下!基础的基础!