#Putting "int" value into "byte" and "short" works, but "long" into "int" not. Why?

1 messages · Page 1 of 1 (latest)

worthy hazel
#
byte b =  10 + 10;
short s = 10 + 10;
int i = 10L; //won't compile: why?

Whats the reason for this? Why does putting the value of a bigger data type (int in this case) work with byte and short, when the assigned value is within the range of what these data types can hold, but not when trying to put long into int?

terse wadiBOT
#

<@&987246399047479336> please have a look, thanks.

rancid mirage
#

hi
there are two things here

  1. 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.)
  2. 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

olive spruce
#

@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;
runic lily
#

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