Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Assignments query [duplicate]

Tags:

java

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.

like image 594
Smith Avatar asked Sep 27 '22 11:09

Smith


1 Answers

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.

like image 54
Pherion Avatar answered Oct 13 '22 02:10

Pherion