2009-03-03 326 views

回答

23

INT = INT +双基本上是

INT =双+双

,你不能做,没有铸造...

的int + =双重力量的结果为int而另一个需要铸造。

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

应该编译。

编辑:按照意见要求...这里是更多的阅读链接(不是最容易读,但最正确的信息):http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

+0

你能否提供一些链接,以便进一步阅读?谢谢 – hhafez 2009-03-04 00:32:30

+0

我认为“深层次”的原因是因为它不允许在缩小时进行赋值:byte = int是不允许的,int也是double。会做一个简单的字节a; a + = 2;并且不能编译,人们会在java上扔鞋子。但我仍然会喜欢额外的规则,使其工作没有演员:( – 2009-03-04 01:20:45

32

在Java + =运营商有一个隐式转换到左手型。这适用于所有组合的操作员。

4

双+ INT返回双,所以 双=双+ int是合法的,见JLS 5.1.2另一方面宽元转换 INT =双+ INT是“基本收缩转换”,需要明确的投

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)