On page 192 of the book, it says that is legal because the compiler automatically narrows the literal value to a byte. However, on page 196, I found that will not compile. I checked this with the default compiler in NetBeans 6.7.1 and it is true. Why does the compiler not automatically narrow the double literal to a float here, just as it does for an int literal to a byte? Just wondering if there is any good reason for this, or is this just an unnoticed bug in the compiler?
My guess is that a double expression will almost always fall outside the representable values of float because they aren't different in just their range of values but also in the precision of those values. Since the precision of a float is different than the precision of a double then the narrowing conversion might substantially change the value being assigned.
*Actually, floating point variables as the type for an assignment narrowing conversion are allowed, but only in the context of Value Set Conversions which isn't really applicable to your question
You're welcome Remember the JLS is not usually an easy read.
That I did find out Tried to figure out the concept of Value Set conversion, just reading what it said in the Assignment Conversions section, but decided after a while that I need to read some other parts to get the full context. Don't worry, I'll figure it out. If not, I'll be back to ask.
Steve Luke wrote:I took a gander at the JLS for Assignment Conversions which specifically talks about assignment narrowing conversions. Other than stating that the variable must be of the integral types* it is pretty silent about why double can't be narrowed to a float.
The JLS doesn't talk about long either -- so no implicit narrowing for long compile time constants to int, short, etc.