Integer to byte casting in Java

前端 未结 5 789
有刺的猬
有刺的猬 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:04

    Hard-coded initializer values are somewhat special in Java - they're assumed to have a coercion to the type of the variable you're initializing. Essentially, that first bit of code effectively looks like this:

    byte b = (byte) 5;
    

    If you did this...

    myObject.testByte((byte) 5);
    

    ...you wouldn't get that error, but if you don't do that, then the 5 is created by default as an int, and not automatically coerced.

提交回复
热议问题