In the first instance the compiler can determine at compile time that the assignment will not cause trouble. In the second example that's not possible because the int isn't final and thus its value isn't fixed at compile time.
The first could be translated into byte b = 100; by the compiler, which is valid. The second cannot be so handled, so the compiler sees you trying to assign a 2 byte value to a 1 byte address space, and complains about that.
Well First There is a rule for the final variable ,which tells that those variables are treated as compile-time constants, that mean that the compiler will treat the final int i as 100 whenever it's used in the code . Second we have a rule that is called Implicit narrowing: that rule inquier a set of conditions to be approved befor it can be applied to the primitve data types variables ,those conditions are: 1- the right most operand must be a constant numeric value (byte,short,char ,,,etc) ,and final variables are treates just like a constant values . 2- the right most operand must be in range of the type specified by the left hand operand : for example consider that we have a byte x variable and number 125 so the assignmnet byte x = 125 will be accepted by the compiler because its fullfill the conditions of implicit narrowing action. Now we return back to the question: the second declaration for the variable i didnt follow neither the conditions mentionend at the rules of implicit narrowing, nor declared as final variable , so as we learned that the default data type for all the intgeral arithmatic operations is int,the variable i (also its declared as int ),will be promoted to int even if it is not declared to be so ,in this case the compiler refuse to assign an int variable to a byte one , and complain the lose of precision . i am sorry for the long comment i hope you will find it useful good luck
thanks to all ranches
[ April 28, 2006: Message edited by: Kaise a.Zakkar ]
"Nothing is harder on your aurels than resting on them."<br />SCJP 1.4 89%,,SCJA 80%,SCWCD1.4 81%
Joined: Apr 25, 2006
So , There is some difference between constant and compile time constant. a little more detail please
Thanks in advance -Neha
Joined: Apr 25, 2006
Originally posted by John Meyers: Sorry about not being more specific...
This is what i meant:
final int i = 10; byte b = i; final int eye; eye = 10; b = eye; // fails
b=eye fails because the final int eye; is not a compile time constant. The value of eye is initialized later, after it has been defined.
but eye is still constant(correct me if i am wrong ). So are there differences between constant and compile constant.
Please expalin, will be really obliged
Joined: Jul 19, 2005
Was not aware of the naming policy ,sorry for that .