I have two functions. One works fine, while the other doesn't compile. Not able to spot the cause. Can you please help me here?
This works fine
static byte method1() {
final short sh1 = 2;
return sh1;
}
This one doesn't compile
static byte method2(final short sh2) {
return sh2;
}
In your first example, sh1
is final
, and has a value which can be determined at compile time to be "castrated down" to a byte
. In effect, it's a constant. If you remove the final
, it won't compile anymore.
In your second example, it cannot be determined by the compiler that your method argument is "safe", you have to do an explicit cast, as other answers mentioned.
For the nitty gritty details, see here (JLS references and all). But a simple example:
final byte b1 = 127;
final byte b2 = 1;
final byte b = b1 + b2; // <-- FAIL: 128 greater than Byte.MAX_VALUE
final byte b1 = 12;
final byte b2 = 3;
final byte b = b1 + b2; // <-- SUCCESS: 15 fits
First Method:
First method you declare a final short
variable whose value is 2
inside the range of byte
. sh1
in that first method cannot hold any other value other than 2
determined at the compile time itself. If you remove the final
, you will see the compiler complaining.
Second Method:
You need to cast short
to byte
as this is a narrowing conversion and you have to assure the compiler that you do it deliberately and know its consequences because final short sh2
can have any value which should or shouldn't be in the range of byte
.
static byte method2(final short sh2)
{
return (byte)sh2;
}
Also as an experiment if you remove assignment from the first one e.g.
static byte method1() {
final short sh1;
return sh1;
}
Then this doesn't compile as well. So just as the second one, the compiler isn't sure about the type safety because the value is passed to the function, same happens if you remove assignment from the first one.
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