繁体   English   中英

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

[英]What is the difference between double a = a + int b and int a += double b?

为什么:

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

编译。

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

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

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

正如每个人都已经说过的那样,+ =有隐式演员。 为了帮助说明这一点,我将使用我之前写的一个应用程序,它非常适合这些类型的问题。 它是一个在线反汇编程序,因此您可以查看正在生成的实际字节码: 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM