#Putting "int" value into "byte" and "short" works, but "long" into "int" not. Why?
1 messages · Page 1 of 1 (latest)
Detected code, here are some useful tools:
byte b = 10 + 10;
short s = 10 + 10;
int i = 10L;
//won't compile: why?
<@&987246399047479336> please have a look, thanks.
hi
there are two things here
- b and s. in java you have to remember that by default every integer constant is either of type int (10) or of type long (10L). so before affection 10 + 10 is an constant expression of type int. for byte, short and char to be usable java allows you to assign them int constants as long as they are represented in the primitve type (max 127 for byte, etc.)
- int and long aren't affected by this rule, because you can already write int or long constants (int by default, L for long). assignment conversions (one type of implicit conversions) exists but they are based on two hierarchies:
byte --> short --> int --> long --> float --> double
or
char --> int --> long --> float --> double
so long --> int isn't a legal assignment conversion, hence the compilation error
you can still force an explicit conversion with the cast operator tho
@worthy hazel It does work
but short -> int is a "widening conversion"
so it can always be done without losing info
long -> int is a "narrowing conversion"
since if you have a big long it will lose that value, java requires you to explicitly cast
int i = (int) 10L;
They are talking about the fact that the first to statements also do narrowing conversion
since 10 + 10 would be an integer, assigning it to a byte would be narrowing
Anyways
In this case Java knows that the result of 10 + 10 fits in a byte, so it will compile
Since those are just constant number values it can make assumptions
But defining a value explicitly as a long will make that not work anymore