Integer to byte casting in Java

前端 未结 5 879
有刺的猬
有刺的猬 2021-01-18 18:43

In Java we can do

byte b = 5;    

But why can\'t we pass same argument to a function which accepts byte

myObj         


        
5条回答
  •  耶瑟儿~
    2021-01-18 19:22

    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.

提交回复
热议问题