Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How explicit casting perform [duplicate]

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 ?

like image 203
Ravi Avatar asked Dec 18 '12 07:12

Ravi


People also ask

What is explicit type 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.

Who performs implicit casting?

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.

Which of the following requires explicit type casting?

Assigning 8 bytes of memory to 1 byte of memory requires explicit casting.

What is explicit and implicit casting in Java?

Java Type Casting is classified into two types. Widening Casting (Implicit) – Automatic Type Conversion. Narrowing Casting (Explicit) – Need Explicit Conversion.


1 Answers

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

Compiler puts the cast automatically.

like image 92
Azodious Avatar answered Oct 16 '22 10:10

Azodious