What exactly is narrowing type conversion in java? -
this question has answer here:
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
, orint
:
- a narrowing primitive conversion may used if type of variable
byte
,short
, orchar
, , 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
Post a Comment