Originally posted by Marco Tedone:
I'm studying the operators and assignments and i have a couple of questions:
1. The author says that implicit narrowing primitive conversions on assignment can occur when the source is an int constant whose value can be determined to be in the range of the destination type at compile time. He also says that the type could be either byte, short or char. In its example the author states that:
byte tiny = (byte) 128; //This because int value is not in range. What does it mean? Is not in range because between byte and int is there short or because of the value?
2. The author says that an int negative value is not determinable and therefore a cast is required, referring to the following example:
int i = -20;
byte b2 = (byte) i; //Value of i not determinable
Why this value is not determinable?
Hope this helps:
The different primative types in Java have what is known as different bit depths (ie: the bit size of the type).
byte 8-bit signed
short 16-bit signed
int 32-bit signed
long 64-bit signed.
To answer your quetion 1. The problem is not with the value or the fact that there is a type between byte and int. The problem is that if you cast an int(32 bits) to a byte(8 bits) without letting the JVM know, explicitly cast, the JVM will complain about "possible loss of precision". If you do this: int i = 20; byte b = (byte)i; You are telling the JVM that you understand that there will be precision loss and you still want to make that assignment. As a result, the compiler makes the conversion for you.
For question 2: I am running v1.4.1 of the JVM under linux. If I do this: int i = -20; long l = i; I get no conversion error.
If I do this: int i = -20; byte b = (byte)i; I get no conversion error.
If I do this: int i = -20; byte b = i; I get a conversion error.
So I guess, in a long winded sort of way, I do not have an answer for your second question.
Hope this helps.