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?
foo
from the array and test that it doesn't change. Its value won't change even iffoo
isn'tfinal
. The assignment (initialization in this case) copies the value at the moment that it happens (1) and that's it. The consequent change offooArray[0]
to 127 will not be automatically propagated tofoo
regardless of if is it final or not.