Integer to byte casting in Java
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 开发者_JS百科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.
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.
Normally, converting an int
to a byte
without an explicit cast is not allowed.
However, if the conversion is part of an assignment, and the value is a statically-known constant that will fit in the destination type, the compiler will perform the conversion automatically.
This special behaviour is described in section 5.2 of the JLS. It is a special case that only applies to assignment; it does not apply to conversions in other contexts.
Now that I think about it, the lack of auto-narrowing for arguments is probably to avoid issues with overload resolution. If I have methods #foo(short)
and #foo(char)
, it's not clear which one foo(65)
should call. You could have special rules to get around this, but it's easier to just require the caller to be explicit in all cases.
You must cast your argument 5
to type byte
in your method testByte
. Java looks specifically at the argument type.
Change it to:
myObject.testByte( (byte) 5);
Integer literals are by default int
in Java. And in myObject.testByte(5);
5
is an integer literal which will be treated as int
.
As all you know Java is strictly types language, so it will not allow to assign an int
to a byte
. All you need to have explicit type-casting.
精彩评论