double a = a + int b和int a + = double b之间有什么区别?

时间:2009-03-03 23:45:55

标签: java types type-conversion operators implicit-conversion

为什么:

public class Addition { 
  public static void main() { 
    int a = 0; 
    double b = 1.0; 
    a = a + b;
    System.out.println(a); 
  }
}

不编译但是:

public class Addition { 
  public static void main() { 
    int a = 0; 
    double b = 1.0; 
    a += b; 
    System.out.println(a); 
  }
}

编译。

4 个答案:

答案 0 :(得分:32)

在Java + =运算符中,左手类型具有隐式强制转换。这适用于所有组合运算符。

答案 1 :(得分:23)

int = int + double基本上是

int = double + double

如果没有施放,你就不能这样做......

int + = double将结果强制为int,而另一个则需要强制转换。

所以a =(int)(a + b);

应该编译。

编辑:根据评论中的要求...这里有更多阅读的链接(不是最简单的阅读,但最正确的信息):http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

答案 2 :(得分:4)

double + int返回double,所以 double = double + int是合法的,请参阅JLS 5.1.2扩展原始转换 另一方面 int = double + int是“Narrowing Primitive Conversion”并需要显式转换

答案 3 :(得分:0)

正如大家已经说过的那样,+ =有隐式演员。为了帮助说明这一点,我将使用我之前写的一个应用程序,它非常适合这些类型的问题。它是一个在线反汇编程序,因此您可以查看正在生成的实际字节码:http://javabytes.herokuapp.com/

并列出其含义: http://en.wikipedia.org/wiki/Java_bytecode_instruction_listings

让我们看一下简单Java代码中的字节码:

int i = 5;
long j = 8;
i += j;

反汇编代码。我的评论将在//前面。

   Code:
        0: iconst_5  //load int 5 onto stack
        1: istore_0  //store int value into variable 0 (we called it i)
        2: ldc2_w #2; //long 8l
                     //load long 8 value onto stack.  Note the long 8l above
                     //is not my comment but how the disassembled code displays 
                     //the value long 8 being used with the ldc2_w instruction
        5: lstore_1  //store long value into variable 1 (we called it j)
        6: iload_0   //load int value from variable 0
        7: i2l       //convert int into a long.  At this point we have 5 long
        8: lload_1   //load value from variable 1
        9: ladd      //add the two values together.  We are adding two longs
                     //so it's no problem
        10: l2i      //THIS IS THE MAGIC.  This converts the sum back to an int
       11: istore_0  //store in variable 0 (we called it i)
相关问题