0

I have the following code:

byte b=10;
System.out.println("Test b:"+b);

This codes is compiled and works without problems. However, I cant understand why. 10 is literal here and it is integer literal (default for integer). So we have here casting as on the left side we have byte and on the right side we have integer. And this is narrowing as byte<integer. As I understand narrowing must always be explicit casting otherwise the code won't compile. Could anyone explain why this code works?

Pavel_K
  • 8,216
  • 6
  • 44
  • 127

2 Answers2

4

It works, because 10 is a compile-time constant. The compiler can infer that it fits the byte range, so it allows the assignment.

You can a play a bit with assigning values to a byte variable. If you for example do

 byte b = 128; 

then you'll get a compilation error, because 128 doesn't fit the byte range. In this case you can do a cast:

 byte b = (byte) 128;

but then you'll end up with an overflow and b will be evaluated to -128.

Konstantin Yovkov
  • 59,030
  • 8
  • 92
  • 140
0

byte's max value is 127.

10 fits in the byte so it is a valid assignment.

try

byte b = 140; //it wont
Konstantin Yovkov
  • 59,030
  • 8
  • 92
  • 140
Uma Kanth
  • 5,614
  • 2
  • 16
  • 40