7

Possible Duplicate:
Java += operator

We can add a value into any variable either b+=8 or b=b+8 both will return the value adding 8 into the variable b. I got the question in my interview, it was

byte b=7;
b=b+8; //compile error

What would be output, I ticked compile time error, since adding byte and int will be int (I believe) and since, we are trying to store int value into byte. But, when I tried below code myself

byte b=7;
b+=8; //OK

Then, the above code compiles and run perfectly without any error and return 15. Now, my question is why and how ? I mean, why it doesn't requires explicit casting ?

Community
  • 1
  • 1
Ravi
  • 30,829
  • 42
  • 119
  • 173
  • may be, since i didn't found the solution. that's why i asked. – Ravi Dec 18 '12 at 07:54
  • `b=(byte) (b+8)` == `b+=8` != `b=b+8` – alexvetter Dec 18 '12 at 07:57
  • Like @alexvetter said, it indeed does an implicit casting. http://stackoverflow.com/questions/8710619/java-operator discusses that. – MC Emperor Dec 18 '12 at 08:02
  • Ya, but that was the one part of my question another question was how ?? i mean how, it perform. But, nevertheless, i'll explore it for more and Thanks everyone.!! – Ravi Dec 18 '12 at 10:07

1 Answers1

1

That's the only difference in b = b + 8 and b += 8

Compiler puts the cast automatically.

Azodious
  • 13,752
  • 1
  • 36
  • 71
  • i know, but that was not question. I asked how and why ?? – Ravi Dec 18 '12 at 07:55
  • How - it is upto compiler. They can add and remove from code as they want cause they are parsing it. Why - for better usability. i.e. developer need not worry about cast during implicit operations. – Azodious Dec 18 '12 at 10:43