Operator + = Java

44

I've always found that the += operator only worked as a shorter form for the traditional increment, for example:

i += j;

Instead of:

i = i + j;

But when performing the following experiment:

int i = 3;
long j = 7;

So when I run i = i + j; it results in error, while i += j; compiles normally.

Given this, is it possible to state that i += j; is actually similar to i = (tipo do i) (i + j); ?

    
asked by Luiz Carvalho 11.01.2014 в 19:28
source

3 answers

47

This is a characteristic of language. As explained in the documentation , the use of operators of type op = includes an casting :

  

A compound assignment expression of the form E1 op = E2 is equivalent   to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1   is evaluated only once.

Original source of the SO response in English.

    
answered by 11.01.2014 / 20:10
source
11

I would like to increase the response by showing how the compiler rates the expression:

int i = 3;
long j = 7;     

 i += j;

The above expression is translated by javac ( J2SE 8 = 52 - 0x34 hex ) in:

ILOAD 1: i  //obtem o inteiro de i
I2L         //converte o inteiro para long
LLOAD 2: j  //obtem o long de j
LADD        //soma os longs (i + j)
L2I         //converte o long para inteiro
ISTORE 1: i //guarda o inteiro em i

Being in practice:

i = (int) ((long) i + j);
    
answered by 08.07.2015 в 15:09
4

When you add different primitive types, where one of them is larger than the other (sum of long with int, or double with int) you need to cast. The compilation error is the JVM informing you that the result of the sum of two numbers that will be assigned in the int can lose value (Ex: add 4.6287 with 1 and put inside int, will only have number 5). When you cast, you inform the JVM that you are aware of this and will take the risks.

When you use i + = j, this is actually what the JVM does: i = (int) (i + j);

    
answered by 13.01.2014 в 12:42