0

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???
}
Aurelian Cotuna
  • 3,076
  • 3
  • 29
  • 49
mRbOneS
  • 121
  • 1
  • 14

1 Answers1

0

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.

Joachim Wagner
  • 860
  • 7
  • 16
  • I dint get what you are saying, in the first case it checks the size of int and byte, and it says type mismatch. We can remove this error by using type casting. My question is why dont we need type casting in second case. – mRbOneS Jun 20 '15 at 05:42
  • 1
    Since z is final, c=z is the same as writing c=30. If you write c=10*z you should get the same compile-time error as if you write c=300. – Joachim Wagner Jul 27 '15 at 13:03