Java中a + = b和a = a + b之间的差异

mmg*_*o27 0 java types operators

我被告知a + = b之间存在差异; 和a = a + b; 这可能导致其中只有一个是合法的,具体取决于类型的变化.

有没有人有这样的例子?

Pet*_*rey 7

基本上没有区别,但有一个细微的差别.

算术赋值运算符执行隐式转换.例如

byte a = 1;
int b = 2;

a += b; // compiles
a = a + b; // doesn't compile as a byte + int = int
a = (byte) (a + b); // compiles as this is the same as +=
Run Code Online (Sandbox Code Playgroud)

对于更奇怪的例子.

int a = 5;
a += 1.5f;
// a == 6

char ch = '0'; // (char) 49
ch *= 1.1;     // ch = '4';

long l = Integer.MAX_VALUE;
l += 0.0f;   // i = (long ) ((long ) l + 0.0f)
// i == Integer.MAX_VALUE + 1L; WTF!?
// l is no longer Integer.MAX_VALUE due to rounding error.
Run Code Online (Sandbox Code Playgroud)