| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
|
Advertisement
|
Why narrowing primitive conversions from primitive long requires explicit casting?Converting a large primitive type to a smaller primitive type is called narrowing primitive conversion. There's a special case known as an assignment conversion that handles some conversion without explicit casting. Let's take a look at the following code:
class Program {
public static void main(String[] args) {
final int iVar = 10;
byte bVar = iVar;
fianl int iVar1 = 345;
byte bVar1 = iVar1; //Compile time error
}
}
In this example, a variable of type byte is being assigned a value of a constant expression of type int. This implies a narrowing conversion. We know that the value of constant expression must be in the range of variable's type for the assignment conversion to happen. In our example, as long as the value of iVar is for -128 to 127, the narrowing conversion is used in the assignment conversion. The following code does not compile, even with the value of constant expression is in the range of type byte:
class Program {
public static void main(String[] args) {
final long lVar = 10;
byte bVar = lVar; //compile time error
}
}
Why the assignment conversion doesn't work here? We have a constant expression and the value is representable for the type byte. Here is answer from JLS:
In the above example, the expression is a constant expression of type long and it is not covered by the special case. Therefore, a explicit cast must be used.
class Program {
public static void main(String[] args) {
final long lVar = 10;
byte bVar = (byte)lVar;
}
}
|