Yes, you can do that.
The value of the
byte
expression will be promoted toint
before it is returned.The actual return type is as declared in the method signature -
int
.
IMO, what the author of that book wrote is more or less correct. He just left out explaining the bit about the byte-to-int promotion that happens in the return
statement when you "return a byte".
Is the cast happening at the end of our method implementation or is the cast happening back in the main method just before assignment?
The cast (promotion) happens in the returnByte
method.
In the real world, this question would not matter as long as one understand the implicit casting and the risk of losing precision.
There is no loss of precision in promoting a byte
to an int
. If the types were different, there could be loss of precision, but (hypothetically) the loss of precision would be the same wherever the promotion is performed.
The section of the JLS that deals with this is JLS 14.17, which says that the return
expression must assignable to the method's declared return type. It doesn't explicitly state that the promotion is done in the method, but it is implied. Furthermore, it is the only practical way to implement this.
If (hypothetically) the conversion was done in the calling method (e.g. main
), then:
- The compiler would need to know what the
return
statement is doing. This is not possible, given that Java classes can be compiled separately. - The compiler would need to know which actual method is going to be called. This is not possible if the method is overridden.
- If the method contained two (or more)
return
statements with expressions that have different types, then the compiler needs to know whichreturn
will be executed. This is impossible.
If this was the real exam and you would have got the question, what would you have answered?
I would have answered ... "it depends" ... and proceeded to the alternative viewpoints.
Technically speaking the method is returning an int
, but the return
statement can take any expression whose type can be converted to an int
.
But if someone said to me that the method is returning a byte
, I would understand what they meant.
Also, as far as i know methods/function use stacks for storage.etc and inside those stacks they store the return addresses not what (type) they are returning to. So, again the ambiguity arises (at least for me). Please correct me if I am wrong.
Yes, technically a method doesn't return a type. (Not even if it returns a Type
object. That is an object that denotes a type, not the type itself.) But everyone and his dog would happily say "the returnByte methods returns type int".
So, if you are going to be pedantic, then yes it is ambiguous. But the solution is to not be pedantic.