Narrowing Type Conversion: Why is assignment of int to a byte in a declaration allowed?

前端 未结 5 1193
孤独总比滥情好
孤独总比滥情好 2021-01-13 10:20

This may sound too trivial for an intermediate Java programmer. But during my process of reviewing Java fundamentals, found a question:

Why is narrowing conversion l

5条回答
  •  不要未来只要你来
    2021-01-13 10:39

    Because a literal number has no type.

    Once you give it a type it must be casted to the other one:

    int i = 13;
    byte b = (byte) i;
    

提交回复
热议问题