Hi Swapna,
If the source and target types are different, type conversion may be necessary when it comes to assigning values to a variable. While
Java takes care of primitive widening conversion (conversion from narrower type to wider type), it requires you to explicitly use a cast for narrowing conversion (conversion from wider type to narrower type).
But Java will perform an implicit narrowing conversion if the following are true.
a) Source value is of type int, char, short or byte
b) Source value is declared final or is a literal value.
c) Source value is within the range of the target type.
If all the above conditions are met, it compiles without an explicit cast. Else a compile error would be thrown.
Since in your code (case1), i is both final as well as int, it compiles.
In code case2, i is int but not final. Hence the compile error.
If you modify this code to include an explicit cast, it will also compile fine.
public class Test{
public static void main(
String []args) {
int i = 100;
byte b = (byte)i; // explicit cast used.
System.out.println(b);
}
}
Hope this helps.
Thanks,
Chintu.