Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is assigning 'int constant -> byte variable' valid, but 'long constant -> int variable' is not?

I have this code snippet:

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

What do you think about it?

Why?

like image 360
gstackoverflow Avatar asked Dec 26 '22 13:12

gstackoverflow


2 Answers

This is defined in the JLS #5.2 (Assignment conversion):

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

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
like image 199
assylias Avatar answered Mar 02 '23 00:03

assylias


Just assuming here because there is unlikely to be a definitive answer.

For

int i = 5l;

the compiler assumes there is a good reason you wrote 5l and not 5 and so it is an error.

For

byte b = 5;

there is no byte literal way of writing 5 and so it would be needlessly pedantic to insist you write (byte) 5 every time and in fact it would be error prone.

byte b = 222;        // is an error
byte b = (byte) 222; // is NOT an error
like image 30
Peter Lawrey Avatar answered Mar 01 '23 22:03

Peter Lawrey