Tuesday 15 December 2015

Exception case in which explicit typecasting is not required in narrowing in Java ( Using Final Keyword )

We all know that in case of narrowing (conversion of higher range data type into lower) explicit typecasting is required. But here is an exception case in which we do not have to explicit typecast in case of narrowing.

1. Int to byte 

Without using final keyword

int i=10;
byte b=i;

Above code will give throw a compile time error as int cannot be assigned to byte. For above program to rum we need to explicitly typecast int to byte.

int i=10;
byte b=(int)i;

This time program will run without giving any error message

Using final keyword

final int i=10;
byte b=i;

In this case

No comments:

Post a Comment