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.