Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

ID : 107

viewed : 272

Tags : javacastingoperatorsvariable-assignmentassignment-operatorjava





Top 5 Answer for Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

vote vote

100

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:

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.

An example cited from §15.26.2

[...] the following code is correct:

short x = 3; x += 4.6; 

and results in x having the value 7 because it is equivalent to:

short x = 3; x = (short)(x + 4.6); 

In other words, your assumption is correct.

vote vote

89

A good example of this casting is using *= or /=

byte b = 10; b *= 5.7; System.out.println(b); // prints 57 

or

byte b = 100; b /= 2.5; System.out.println(b); // prints 40 

or

char ch = '0'; ch *= 1.1; System.out.println(ch); // prints '4' 

or

char ch = 'A'; ch *= 1.5; System.out.println(ch); // prints 'a' 
vote vote

76

Very good question. The Java Language specification confirms your suggestion.

For example, the following code is correct:

short x = 3; x += 4.6; 

and results in x having the value 7 because it is equivalent to:

short x = 3; x = (short)(x + 4.6); 
vote vote

60

Yes,

basically when we write

i += l;  

the compiler converts this to

i = (int)(i + l); 

I just checked the .class file code.

Really a good thing to know

vote vote

52

you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like

i = i + (int)l; 

or

i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly. 

but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.

Top 3 video Explaining Why don't Java's +=, -=, *=, /= compound assignment operators require casting?







Related QUESTION?