Java += operator

Asked

Viewed 12,951 times

47

I always thought the operator += functioned only 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 execute i = i + j; 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);?

  • 1

    Only to the character of curiosity I tested in language Objective-C and worked the function that gave error in your code in Java, I’ll dig deeper into that question.

  • 1

    @iTSangar I believe the error lies in mixing two types of data during the operation, so the need for a type casting: i = (int) (i+j);, I think...

  • 2

    I think it’s cool this kind of question because it demystifies things that people learn intuitively wrong. And intuition without a solid knowledge of the most damaging subject of help.

3 answers

50


This is a feature of language. How explained in the documentation, the use of operators of type op= includes a casting implicit:

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 response in the OS.

12

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

int i = 3;
long j = 7;     

 i += j;

The above expression translates to 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);

5

When you add different primitive types, where one is larger than the other (sum of long with int, or double with int) you need to cast. The build 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 the int, it will only have the number 5). When you cast, you inform JVM that you are aware of this and will take the risks.

When you use i += j, that’s actually what the JVM does: i = (int)(i + j);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.