Monday, May 7, 2018

Why does Java require an explicit cast on a final variable if it was copied from an array?

Starting with the following code...


byte foo = 1;
byte fooFoo = foo + foo;

When I try compiling this code I will get the following error...



Error:(5, 27) java: incompatible types: possible lossy conversion from int to byte



... but if foo is final...


final byte foo = 1;
final byte fooFoo = foo + foo;

the file will compile successfully.


Moving on to the following code...


final byte[] fooArray = new byte[1];
fooArray[0] = 1;
final byte foo = fooArray[0];
fooArray[0] = 127;
System.out.println("foo is: " + foo);

... will print


foo is: 1

... which is fine. The value is copied to a final variable and it can not be changed any more. Playing with the value in the array does not change the value of the foo (as expected...).


Why does the following require a cast?


final byte[] fooArray = new byte[1];
fooArray[0] = 1;
final byte foo = fooArray[0];
final byte fooFoo = foo + foo;

How is this different than the second example in this question? Why is the compiler giving me the following error?



Error:(5, 27) java: incompatible types: possible lossy conversion from int to byte



How can this happen?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...