double a = a + int b 和 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 中,+= 运算符隐式转换为左侧类型.这适用于所有组合运算符.

In Java += operator has an implicit cast to the left hand type. This goes for all composed operators.

相关文章