According to my knowledge in Java, in narrowing type conversion if source in any constant which is in range of byte than the following is allowed:
byte b=10; // allowed because 10 is in range of byte and 10 is a constant
but when I type this:
byte b=10l; // this is not allowed although 10 is in range of byte and is a constant
Why so ? Can you please tell the exact rule by which these narrowing conversions take place in Java.
The technical answer is — because the spec says so. §5.2 "Assignment Contexts" of The Java Language Specification, Java SE 8 Edition, states in part:
In addition, if the expression [on the right-hand-side of an assignment statement] is a constant expression (§15.28) of type
byte
,short
,char
, orint
:
- A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, and the value of the constant expression is representable in the type of the variable.
As for why it doesn't allow the constant expression to be of type long
, I suppose it's that you never "accidentally" end up in type long
. It is very convenient to be able to write byte b = 127
as a shorthand for byte b = (byte) 127
while having the compiler prevent you from erroneously writing byte b = 128
as shorthand for byte b = (byte) 128
; it is not so useful to able to write byte b = 127L
, specifically, because why would you need that?