What exactly is narrowing type conversion in java? -


according knowledge in java, in narrowing type conversion if source in constant in range of byte following allowed:

byte b=10; // allowed because 10 in range of byte , 10 constant 

but when type this:

byte b=10l; // not allowed although 10 in range of byte , constant  

why ? can please tell exact rule these narrowing conversions take place in java.

the technical answer — because spec says so. §5.2 "assignment contexts" of the java language specification, java se 8 edition, states in part:

in addition, if expression [on right-hand-side of assignment statement] constant expression (§15.28) of type byte, short, char, or int:

  • a narrowing primitive conversion may used if type of variable byte, short, or char, , value of constant expression representable in type of variable.

as why doesn't allow constant expression of type long, suppose it's never "accidentally" end in type long. convenient able write byte b = 127 shorthand byte b = (byte) 127 while having compiler prevent erroneously writing byte b = 128 shorthand byte b = (byte) 128; not useful able write byte b = 127l, specifically, because why need that?


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -