问题
class MyClass {
void myMethod(byte b) {
System.out.print("myMethod1");
}
public static void main(String [] args) {
MyClass me = new MyClass();
me.myMethod(12);
}
}
I understand that the argument of myMethod()
being an int
literal, and the parameter b
being of type byte, this code would generate a compile time error. (which could be avoided by using an explicit byte cast for the argument: myMethod((byte)12)
)
class MyClass{
byte myMethod() {
return 12;
}
public static void main(String [ ] args) {
MyClass me = new MyClass();
me.myMethod();
}
}
After experiencing this, I expected that the above code too would generate a compile time error, considering that 12 is an int
literal and the return type of myMethod()
is byte. But no such error occurs. (No explicit cast is needed: return (byte)12;
)
Thanks.
回答1:
Java supports narrowing in this case. From the Java Language Spec on Assignment Conversion:
A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, and the value of the constant expression is representable in the type of the variable.
回答2:
From Java Primitive Data Type reference:
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
Try returning 128 : ))
回答3:
This will work byte b = 4
as long as value is within the range, but if you try something like byte b = 2000
you would get compiler error because it is out of range. 12
is in within range so you aren't getting error.
来源:https://stackoverflow.com/questions/13915143/why-is-an-explicit-cast-not-needed-here