Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return values in a static function - Java

Tags:

java

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;
}
like image 248
Edi Nijam Avatar asked Jun 18 '13 09:06

Edi Nijam


3 Answers

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
like image 173
fge Avatar answered Oct 28 '22 05:10

fge


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 2determined 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; 
}
like image 25
AllTooSir Avatar answered Oct 28 '22 05:10

AllTooSir


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.

like image 32
voidMainReturn Avatar answered Oct 28 '22 05:10

voidMainReturn