Java Assignments Request

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. } 

Conclusion: Compilation error: method fun(byte) is not applicable for the argument (int).

My question is:. How is it that 1, 7 implicitly discarded in byte from int , and in case 2 it forces the programmer to express it explicitly?

7 is still in the byte range.

Please offer.

+5
source share
4 answers

Numeric literals such as 7 are treated as integers. So usually, as in your second case, you need to send to byte to pass it where byte is expected.

 fun((byte)7); // You are forced to cast here. 

However, your first case is special because you use this integer literal in a variable initialization statement. In this case, there is a rule in JLS that allows implicit casting.

 byte b = 7; // special JLS rule applies, the cast is done for you automatically. 

JLS Spec

Furthermore, if the expression is a constant expression (ยง15.28) of type byte, short, char or int:

Narrowing down a primitive conversion can be used if the type of the variable is a byte, short, or char, and the value of the constant expression is represented in the type of the variable.

+1
source

In case 1, you implicitly throw String, which is output to standard output. On the other hand, your function requires a byte, not an integer.

+2
source

In fun(7) , 7 is an integer literal.

Try the following:

 fun((byte)7); // explicit cast, compile fine 

Now comes to your question:

In case 1, byte b = 7; and System.out.println(b); are in the same area. Since 7 is suitable for byte , there is no need for explicit casting, and println(b) just discards the byte into string and prints 7 .

But in In case 2 they do not match. You call fun with Integer 7 from one area, where the called function in another area takes instead of byte int . Therefore, it does not matter whether 7 is suitable in byte or not, therefore, a compiler build error (request for explicit casting) before executing the System.out.println(b); program System.out.println(b); .

+1
source

By default, 7 is an int literal. in the first case: - byte b = 7; we explicitly assign int literal 7 to byte b , therefore, implicitly java processes it and assigns the corresponding value int 7 to byte , which is also equal to 7 , which means that casting / conversion is performed implicitly by java.

But in the second case, fun(7); type 7 here is int by default, but your fun(byte) method expects byte as a parameter not int , and since java is strictly leading, it gives an error.

0
source

All Articles