Converting from Java primitive to wrapper classes

前端 未结 3 2172
谎友^
谎友^ 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:44

    This seems to be compiler-specific behavior. When I paste your code into Eclipse, running Java 7, I do not see the compiler errors you report for short to Integer or byte to Integer.

    Instead, I see byte, short, and int can all be assigned to Byte, Short, and Integer, but not Long, and long can only be assigned to Long. Interestingly, if you change the variables to primitives instead of wrapper types, the byte, short, and int behavior doesn't change, but now the assignments from the other types to long also work.

    javac 1.7.0_02
               | byte | Byte || short | Short || int | Integer || long | Long |
    From byte  | Yes  | Yes  || Yes   | Yes   || Yes | No      || Yes  | No   |
    From short | Yes  | Yes  || Yes   | Yes   || Yes | No      || Yes  | No   |
    From int   | Yes  | Yes  || Yes   | Yes   || Yes | Yes     || Yes  | No   |
    From long  | No   | No   || No    | No    || No  | No      || Yes  | Yes  |
    
    Eclipse Indigo
               | byte | Byte || short | Short || int | Integer || long | Long |
    From byte  | Yes  | Yes  || Yes   | Yes   || Yes | Yes     || Yes  | No   |
    From short | Yes  | Yes  || Yes   | Yes   || Yes | Yes     || Yes  | No   |
    From int   | Yes  | Yes  || Yes   | Yes   || Yes | Yes     || Yes  | No   |
    From long  | No   | No   || No    | No    || No  | No      || Yes  | Yes  |
    

    Given that different compilers allow different conversions, I suspect the "correct" behavior is not actually spelled out in the JLS. It seems certain conversions are done under the covers because the compiler writers considered it convenient (e.g. byte a = (int)1 is allowed but byte a = (int)1000 is not), not because it's a documented part of the language.

提交回复
热议问题