CASE 1
byte b = 7; // why don't I need to cast 7 to byte in this case? byte b = (byte)7;
System.out.println(b);
Output: 7
CASE 2
static void fun(byte b) {
System.out.println(b);
}
public static void main(String []args) {
fun(7); // Compiler gives error because a cast is missing here.
}
Output:
Compilation error: method fun(byte) is not applicable for the argument (int).
My question is: How come in case 1, 7
is implicitly cast to byte
from an int
, while in case 2 it is forcing the programmer to cast it explicitly?
7
is still in the range of byte
.
Please suggest.
In case 1, you are implicitly casting to String, which is what gets pumped out to the standard output. Your function on the other hand, requires a byte, not an integer.
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