| Author |
Using Final Keyword & Casting
|
Chatura Dilan
Greenhorn
Joined: Apr 22, 2006
Posts: 16
|
|
Compare following code public class Cat{ public static void main(String args[]){ int x = 20; byte y = 10; y = x; System.out.println(y); } } Compilation Error java:8: possible loss of precision found : int required: byte y = x; ^ 1 error Above code is OK, because I have to do casting like this y =(byte) x; but look at this public class Cat{ public static void main(String args[]){ final int x = 20; byte y = 10; y = x; System.out.println(y); } } This example prints 20 and no compilation error I do not understand why it implicitly converts int to byte, when I use final keyword. Thanks in advance.
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
This is a situation of a narrowing primitive conversion. Basically the reason that it works is that because the int value on the right of the assignment statement is a compile-time constant, and its value is compatible with a byte, the compiler will accept the assignment.
|
 |
 |
|
|
subject: Using Final Keyword & Casting
|
|
|