In Java we can do
byte b = 5;
But why can't we pass same argument to a function which accepts byte
myObject.testByte(5);
public void testByte (byte b)
{
System.out.println("Its byte");
}
It gives following error
The method testByte(byte) in the type Apple is not applicable for the arguments (int)
PS: May be a silly question, I think I need to revise my basics again.
Thanks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With