Implicit narrowing rules in java

788 views Asked by At
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.

2

There are 2 answers

1
M Alok On

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:

byte b=(byte)0L;

Then there will be no compiler error, as you are telling compiler explicitely for the conversion.

5
Jesper On

The L suffix on the literal 0L makes this literal of type long (a 64-bit signed integer).

There is no implicit narrowing from long to byte, according to the rules of the Java language.

See Java Language Specification section 5.2 Assignment Contexts:

In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

Note that the type of the constant expression does not include long.