class MyClass { public static void main(String []args) { final int i = 100; byte b = i; System.out.println(b); } } ------------------------------------------------ class MyClass { public static void main(String []args) { int i = 100; byte b = i; System.out.println(b); } } ----------------------------------------------- The top class compiles and prints 100. The bottom class gives compiler error, stating possible loss of percision, why please?
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
posted
0
You can't assign an int to a byte without a cast. It is considered a narrowing conversion and data might be lost. In the first case, however, we use the keyword final, which makes that value a compile-time constant. Therefore, the compiler can check to see if the value is within the range of a byte for the assignment. This can't be done if the variable is not final. That's why the second one gives a compiler error while the first one doesn't. I hope that helps, Corey