Assigning int to byte in java

Viewed 88

In java, it is fine to have:

byte b = (int) 2;

where java automatically convert int to byte. On the other hand, if we do:

int a = 2;
byte b = a;

this will give an error saying that the required type is byte but int is provided.

May I ask how to understand the reason why automatic conversion works when literal number of type int is assigning to a variable of type byte while it doesn't work when the literal number is replaced by a variable of type int?

Thanks in advance!

1 Answers

It is fine to have

byte b = (int) 2;

Because 2 is casted into int and than it is the same as

byte b = 2;

The following also works

int a = 2;
byte b = (byte) a;
Related