If you return a constant, the compiler is smart enough to see that it fits into a byte and will cast it implicitly for you. If you would have used a value that would not fit in a byte, for example:
Then you would have gotten a compiler error.
This special handling doesn't work when you're trying it with a variable instead of a constant, because the compiler in principle can't be sure, by only looking at the return statement, if the value of the variable will fit into a byte.
The first one compiles but the second one doesn't. My understanding was, java takes in any number literal as an integer, in which case both shouldn't compile.. Thanks.
There is huge difference in returning call.
"return 42;", here compiler wants a byte to be return. So Compiler will implicitly type converted to byte.similar to
if you see the second example,"int i=42; return i;".It is obvious, you are returning an int value, which need explicit type conversion. Complier will flag a error. It is similar to below statement :
b=b+13;// here compiler will raise an error.Why?
Please remember the following sequence for implicit conversion
byte --> short --> int -->long -->float-->double
if you try to go in reverse, then you need to do explicit type casting. Even you have to do explicit type casting in the case of short( or byte) to char primitive types.