In Java we can do
byte b = 5;
But why can\'t we pass same argument to a function which accepts byte
myObj
The reason is that when you are narrowing a primitive, you must explicitly make a cast - so you acknowledge a possible loss of data.
To illustrate, when casting 5
there is no loss because the value is within the -128...127
byte value range, but consider a larger int
value, say 300
- if you cast to byte, you must throw away some bits to make it fit into 8 bits.
The topic is covered in full here.