I have this piece of code:
int i = 5l; // not valid (compile error) byte b = 5; // valid
What do you think about this?
Why?
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
, .
int i = 5l;
, , 5l, 5, .
5l
5
byte b = 5;
byte 5, , (byte) 5 .
byte
(byte) 5
byte b = 222; // is an error byte b = (byte) 222; // is NOT an error
( , 5, 127 128 ):
byte b = 127;
:
byte b = 128;
JLS:
, (§ 15.28) , , char int:, , char, .
, (§ 15.28) , , char int:
, , char, .
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
, -
5l - , (§15.28) byte, short, char int. , , int, bacause , - , char.
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
, , int i = 5l; , , , , , int .
int range: -2147483648... 2147483648, : -2 ^ 63... 2 ^ 63-1
,
long int, , i.e
int i = (int) 5l;
, , int,
, int
byte b= 5; ????
, , -128 127,
.
Source: https://habr.com/ru/post/1526933/More articles:Postgresql - есть ли способ отключить отображение инструкций INSERT при чтении из файла? - postgresqlTry the Linq query - c #How does the mozilla stub installer work? - google-chromeknockoutjs radio integer databind not working for verification - data-bindingAndroid: how to call MediaController to fast forward and rewind using KeyEvents - androidhtaccess does not redirect to codeigniter - phpwebview clipped to ios7 - iosreplace space in text without affecting html tags - htmlFacebook uses the wrong image and text after sharing - phpIn a CQRS architecture without an explicit read model, which processor updates the data store? - design-patternsAll Articles