Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "+=" operator do in Java?

Tags:

java

Can you please help me understand what the following code means:

x += 0.1; 
like image 530
Kotaro Ezawa Avatar asked Sep 17 '11 17:09

Kotaro Ezawa


People also ask

What is << in Java?

Left shift operator shifts the bits of the number towards left a specified number of positions. The symbol for this operator is <<.

What is the operator used for?

An operator is used to manipulate individual data items and return a result. These items are called operands or arguments.

What is the use of && and || operator in Java?

&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true.


2 Answers

The "common knowledge" of programming is that x += y is an equivalent shorthand notation of x = x + y. As long as x and y are of the same type (for example, both are ints), you may consider the two statements equivalent.

However, in Java, x += y is not identical to x = x + y in general.

If x and y are of different types, the behavior of the two statements differs due to the rules of the language. For example, let's have x == 0 (int) and y == 1.1 (double):

    int x = 0;     x += 1.1;    // just fine; hidden cast, x == 1 after assignment     x = x + 1.1; // won't compile! 'cannot convert from double to int' 

+= performs an implicit cast, whereas for + you need to explicitly cast the second operand, otherwise you'd get a compiler error.

Quote from Joshua Bloch's Java Puzzlers:

(...) compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion [JLS 5.1.3].

like image 96
jakub.g Avatar answered Sep 19 '22 22:09

jakub.g


  • x += y is x = x + y
  • x -= y is x = x - y
  • x *= y is x = x * y
  • x /= y is x = x / y
  • x %= y is x = x % y
  • x ^= y is x = x ^ y
  • x &= y is x = x & y
  • x |= y is x = x | y

and so on ...

like image 39
Eng.Fouad Avatar answered Sep 19 '22 22:09

Eng.Fouad