byte b = 0xFFFFFFFF; //OK, because integer -1 sits between -128 and 127, FINE!!
char ch = 0xFFFFFFFF; //Not OK, because integer -1 does not sit between 0 and 65535, FINE!!
byte b = 0L; //Compiler says Not OK? But long integer 0 sits between -128 and 127?
I am not convinced with narrowing rule applied by the java compiler in third line of above code.
Please help me understand, the logic behind this narrowing rule.
There are two ways of casting a primitive data type into another. Explicit and Implicit.
Implicit casting as in your case
byte b = 0L;
gives compilation error as there is a possible loss of information.If you change it like this:
Then there will be no compiler error, as you are telling compiler explicitely for the conversion.