Wrapper classes - why integer literals fail for Long but work for anything smaller

前端 未结 2 1354
迷失自我
迷失自我 2020-12-10 14:35

Just trying to understand auto-boxing, which I do apart from one thing:

Short s = 250;
Long l = 250;

The assignment to Long l

2条回答
  •  春和景丽
    2020-12-10 14:42

    Ideally, no auto narrowing should be allowed.

    But since there are no byte/short literals, we can't write

    byte b = 0b;
    

    and it seems silly to

    byte b = (byte)0;
    

    so auto narrowing of constant integer is allowed so we can write

    byte b = 0;
    

    which is carried over to autoboxing case.

    For long/Long, since there are long literals, this is less of a problem. Still, it should be allowed, since auto widening of signed integer is always safe.

提交回复
热议问题