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.
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.
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 : ))
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