These are the JLS rules for a permitted narrowing integer conversion:
a narrowing primitive conversion may be used if all of the following conditions are satisfied:
* The expression is a constant expression of type byte, short, char or int. * The type of the variable is byte, short, or char. * The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
That is why "final int i = 100;" makes "byte b = i;" legal but "int i = 100;" does not. A final variable is a constant expression, but a non-final variable is not.
Because i is a constant expression in one, and not in the other. JLS 15.28 if I remember rightly.
Tony Morris Java Q&A (FAQ, Trivia)
posted 14 years ago
i reading K&T. is it necessary to read the JLS as most of the explanation discussed in forums are from JLS.
First of all, many of the SCJP mock exams ask questions a litle harder than the actual SCJP exam. Since K&B know what is in the exam, they only cover exam topics. So many JavaRanch questions are not fully answered in K&B.
Almost all Java questions are answered in the JLS and the API documentation, and this material is correct by definition. If the real SDK behaves differently, that is a bug (I know one JavaRancher who disagrees with this). In addition, working Java programmers need to know how to use this material easily. Finally, the stuff is available for free at the Sun Java web site, so everyone has a copy. That is why we often answer questions by quoting the JLS and API doc. [ March 23, 2005: Message edited by: Mike Gershman ]
The value of final variable cannot be changed during the execution. So, final int i=100; i always have value 100. byte b=i is legal since 100 is fit to range of byte. But final int i=129; byte b=i is illegal.
(2) int i=100; byte b=i is legal because the value of i can be changed during the program execution.
posted 14 years ago
Sorry, please ignore pt(2) on my previous post. It should be like this
(2) int i=100; byte b=i is illegal because the value of i can be changed during the program execution.
int i=100; byte b=i; is illegal because the value of i can be changed during the program execution.
A better way to say this that i is not a compile-time constant. Consider a blank final variable:
i cannot be changed after it is initialized in the constructor, but i is not a compile-time constant so a narrowing primitive conversion is not allowed. [ March 24, 2005: Message edited by: Mike Gershman ]