有哪位仁兄知道java 中 += 的底层原理吗, 比如类型转换之类等 小弟对原理比较入迷

解决方案 »

  1.   

    什么原理,int(i,b) i+=b,就是i=i+b,如果是类类型的无非就是类型转换罢了。
      

  2.   

    关键lz想要的就是类型转换问题,比如,
    int i = 0;
    i += 1;
    i += 'a';
    i += 1.2d;
    i += 353534444345345345L;
    i += 3.2f;
    byte b = 7;
    i += b;
    i += (byte) 7;
    i += (char) 65;
    等牛人解释。。
      

  3.   

    不需要理解的太复杂吧?基本上就是自动帮你加个强转而已。比如:
    i += expRight;
    约等于
    i = (int) (i + expRight);
      

  4.   

    首先char类型是能够转换成int型的,这不需要解释。
    i+=1.2d以及以下的。
    首先将该表达式转化以下i=i+1.2d;
    就是将1.2d转化成int在与int i相加。
    所以结果是int类型的
      

  5.   


    这个说法不对。不是先把1.2d转化为int再去计算;而是先把右边按常规情况计算完毕,再进行强转,而且这个计算过程,等式左边的变量是直接参与的。比如:
    int i = 2;
    i *= 1.6d;
    结果 i == 3其实就是:
    int i = 2;
    i = (int) (i * 1.6d); 
    // 计算过程中,会先升级为double进行运算,得到3.2,最后才强转为3。
      

  6.   


    from:java language specification15.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);