Converting from Java primitive to wrapper classes

前端 未结 3 2170
谎友^
谎友^ 2021-02-09 23:22

I am mystified by the behavior of the Java compiler when assigning primitives to wrapper class references. Please see the code below. The lines with comments don\'t compile.

3条回答
  •  北海茫月
    2021-02-09 23:49

    From my research, I found that a byte is an 8-bit signed integer. Shorts are 16-bit signed integers. Therefore I can see why they are compatible, they are both two's complement signed integers, emphasis on signed. A long is a 64-bit integer, but it can also be unsigned (considering it has methods for comparing unsigned longs). This would probably explain why your conversions to long are causing errors - you'd be casting a signed byte to a potentially unsigned long. (Source: Reading about primitives at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)

提交回复
热议问题