Java widening conversions

后端 未结 5 1005
时光取名叫无心
时光取名叫无心 2020-12-28 14:55

I\'m preparing for Java 7 certification and have the following question.

Byte b = 10 compiles ok. Looks like the compiler is narrowing int 10 to byte 10

5条回答
  •  滥情空心
    2020-12-28 15:36

    i think i have a solution for your problem...

    //constructor for Byte class
    Byte(byte value){
    
    }
    

    There are two rules for java type conversion

    1. Both types are compatible
    2. Destination type is greater than source type

    Now in Your case you trying to convert int into byte which is against our second rule.... but below is the solution

    Byte b = new Byte((byte)10);
    

    Now let's talk about your Second issue...

     Long x = 10;//incompatible type
    

    This is the issue of autoboxing... Now as we all know that autoboxing automatically converted primitive type into it's wrapper class.. But conversion not happens in case of autoboxing means....int is converted into Integer byte is converted into Byte.. Now when you assign int primitive type to Long, it gives you error of incompatible type....... Solution

    Long x = (long) 10;//works fine....
    

提交回复
热议问题