30

为什么:

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

4 回答 4

32

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

于 2009-03-03T23:49:30.077 回答
23

int = int + double 本质上是

整数 = 双 + 双

如果没有铸造,你就无法做到这一点......

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

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

应该编译。

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

于 2009-03-03T23:49:03.400 回答
4

double + int 返回 double,因此 double = double + int 是合法的,另一方面,请参见 JLS 5.1.2 Widening Primitive Conversion int = double + int 是“Narrowing Primitive Conversion”并且需要显式转换

于 2009-03-04T00:26:08.460 回答
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)
于 2013-02-27T12:15:12.540 回答