Why is the value 'int constant & # 8594; byte variable 'valid, but' long constant & # 8594; int variable 'is not?

I have this piece of code:

int i = 5l; // not valid (compile error)
byte b = 5; // valid

What do you think about this?

Why?

+4
source share
6 answers

This is defined in JLS # 5.2 (Assignment Conversion) :

If the expression is a constant expression (§15.28) of type byte, short, char or int, then narrowing the primitive conversion can be used if the variable type is byte, short or char, and the value of the constant expression is represented in the variable type.

So:

byte b = 5; //ok: b is a byte and 5 is an int between -128 and 127
byte b = 1000; //not ok: 1000 is an int but is not representable as a byte (> 127)
byte b = 5L; //not ok: 5L is a long (and not a byte, short, char or int)
int i = 5L; //not ok: i is not a byte, short or char
int i = 5; byte b = i; //not ok: i is not a constant
final int i = 5; byte b = i; //ok: i is a constant and b is a byte
+8
source

, .

int i = 5l;

, , 5l, 5, .

byte b = 5;

byte 5, , (byte) 5 .

byte b = 222;        // is an error
byte b = (byte) 222; // is NOT an error
+1

( , 5, 127 128 ):

    byte b = 127; 

:

    byte b = 128;

JLS:

, (§ 15.28) , , char int:

, , char, .

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

, -

int i = 5l;

5l - , (§15.28) byte, short, char int. , , int, bacause , - , char.

+1

int i = 5l;  // trying to allocate 64bits in 32 bits space. Err

as

byte b = 5; //  byte can represented in a  range is -128 to 127. Compiles fine
0

, , int i = 5l; , , , , , int .

int range: -2147483648... 2147483648, : -2 ^ 63... 2 ^ 63-1

0

,

long int, , i.e

int i = (int) 5l;

, , int,

, int

byte b= 5; ????

, , -128 127,

.

0

Source: https://habr.com/ru/post/1526933/


All Articles