Program 1 :
----------
public class SCJP{
public static void main(String[] args) {
final int x = 10;
short y = x ;
System.out.print(x);
System.out.println(y);
}
}
This is a case of implicit narrowing conversion...Generally, narrowing conversion requires explicit casting. But narrowing conversion can also be done implicitly provided the following 3 conditions are satisfied :
1. The source (in this case, it is x) is a constant expression of either byte, short, char, or int type
2. The destination type (in this case, it is y) is either byte, short, or char type
3. The value of the source is
determined to be in the range of the destination type
at compile time Coming back to program 1 : First look at the statement
Here you are assigning a integer value to a short variable. So, this is narrowing conversion. Now, you need to find out whether you need an explicit casting or not.. here, final variable x is assigned a value of 10 during the declaration stage itself..so, x becomes a compile time constant & thus satisfying condition # 3. As you can see, conditions 1 & 2 are already satisfied.. thus it becomes
implicit narrowing conversion..
Program 2 :
-----------
public class SCJP{
public static void main(String[] args) {
final int x;
x = 10;
short y = x ;
System.out.print(x);
System.out.println(y);
}
}
In this case, you are NOT assigning the value of 10 to the final variable x during the declaration stage itself.. so, now, the value of x can be changed elsewhere in the program..in other words, you can say that the compiler will treat x as just another normal variable.. so, x is not a COMPILE TIME CONSTANT anymore and thus not satisfying condition # 3..
Because of this reason, you need to explicitly cast the narrowing conversion in order to make program # 2 work..
i.e. short y = (short) x ;
Hope this can solve your doubt..
Do let me know if you have any queries, I will try to explain it in a better way..
regards,
naveen
" It's the attitude and not the aptitude that determines the altitude"