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.
Well type checks happened on the variable type, and not on the values. So if you try to assign any int variable value to byte variable, it won�t compile.
You need to change your code as below to compile the code
The i's value must be within the range of byte (-128 to 127), otherwise it is generating a compiler error. [ August 16, 2006: Message edited by: wise owen ]
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;
AND
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
Any ideas on why long is treated differently here? (I find it helpful to know "why" when learning language rules, and this one seems a little arbitrary on first glance.)
I found This post, which gives a reasonable justification for treating long differently.
Vaibhav Chauhan
Ranch Hand
Joined: Aug 16, 2006
Posts: 115
posted
0
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.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: Plz explain me the answer of this code........