assign byte to Final Integer

79 views Asked by At

Can a variable of type int that has been declared final be assigned to a byte data type variable? Why?

public class ByteDataType {
    public int x=20;
    byte a=x;                 //This is an error 
    public final int z=30;
    byte c=z;                 // This is not an Error !! Why???
}
1

There are 1 answers

2
Joachim Wagner On BEST ANSWER

I'd guess it's because the compiler can easily check whether z is in range at compile time since it is constant (final) but for x it would take a bit more effort on the compiler to check that x cannot have changed since the initialisation and the people who wrote the specifications for this programming language decided to forbid a=x to make life easier for the compiler.