This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Interesting, I would expect a compile error: possible loss of precision for the first block of code.
The code compiles when we have:
final short i = 100; byte b = i;
final int i = 100; byte b = i;
Could this be because the byte(8 bit), short(16 bit) and int (32 bit) all fall in the range of a 32-bit register and the long primative type has a 64 bit size and therefore loses 32 bits when assigned to a byte or an int?
In addition, if the expression is a constant expression (�15.28) of type byte, short, char or int : � A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is represent- able in the type of the variable. FT
I found This post, which gives a reasonable justification for treating long differently.
Joined: Aug 16, 2006
As per my view towards the implicit narrowing is that.... the reason for allowing the implicit narrowing for:
// code: final int i=100; byte b=i;
is that literals can never be byte,short or char type so whenever there is any need to asign a constant value to a variable of type byte,short or char ,java tells why should we bother about converting the int literal (in above case, 100) explicitly to byte before assigning it to variable b.... because in any case its not possible to assign 100 as a byte to variable b. But in case of following codes:
//code: final long l=100; byte b=i;
// code: final long l=100; int i=l;
....java compiler tells that we should cast it explicitly to remove ambiguity or any confusion.