0
byte b;
b= b+10;

and

byte b;
b+=10;

The first instance gives an error while the second gives correct output can anyone explain the internal operation here

Bentaye
  • 9,403
  • 5
  • 32
  • 45
Varun
  • 1
  • 1
  • 5
    In Java, both these statements will produce a compilation error – Arthur Attout Sep 08 '18 at 10:48
  • Look at this: https://stackoverflow.com/questions/8710619/why-dont-javas-compound-assignment-operators-require-casting – Rahim Dastar Sep 08 '18 at 11:22
  • In Java, `byte b;` and then doing something with `b` before initializing it causes a compile error. Change `byte b;` in your examples to `byte b = 0;` to make them meaningful. – Erwin Bolwidt Sep 08 '18 at 11:51

1 Answers1

0

b += 10 means

  1. Find the place identified by x
  2. Add 10 to it

But b = b + 10 means:

  1. Find the place identified by b
  2. Copy b into an accumulator
  3. Add b to the accumulator
  4. Store the result in b
  5. Find the place identified by b
  6. Copy the accumulator to it

Both the result will be the same but b+=10 will be preferred over b=b+10. You can find more detail here in this answer:

https://softwareengineering.stackexchange.com/questions/134118/why-are-shortcuts-like-x-y-considered-good-practice

imsaiful
  • 1,556
  • 4
  • 26
  • 49