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 ?
Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.
Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present.
Assigning 8 bytes of memory to 1 byte of memory requires explicit casting.
Java Type Casting is classified into two types. Widening Casting (Implicit) – Automatic Type Conversion. Narrowing Casting (Explicit) – Need Explicit Conversion.
That's the only difference in b = b + 8
and b += 8
Compiler puts the cast automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With