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?

2
  • long x = 1; this compiles too. but int x = 100000000000000; wont Commented Aug 19, 2015 at 6:54
  • 2
    Here is a nice explanation. Commented Aug 19, 2015 at 6:55

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Then could you explain why float f=23.22 not work? 23.22 also fits float range...
The floating point values are something else - checkout the JLS
0

byte's max value is 127.

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

try

byte b = 140; //it wont 

Comments