Monday, 7 May 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...