Boxing and Widening

前端 未结 7 1676
小蘑菇
小蘑菇 2020-12-30 08:22

What is the difference between these two. I know Boxing is converting primitive values to reference. What is widening. Also what should be the sequence first boxing should b

7条回答
  •  不思量自难忘°
    2020-12-30 09:17

    Widening is the extension of data type into a wider type. Boxing is when primitive data type is wrapped into a container object so that it can be used in Generics, mainly Collections. Eg:

    public class Widening{
    public static void main(String[] args) throws Exception {
    int test = 20;
    myOverloadedFunction(test);
    }
    //static void myOverloadedFunction(long parameter) {
    //System.out.println("I am primitive long");
    //}
    static void myOverloadedFunction(Integer parameter) {
    System.out.println("i am wrapper class Integer");
    }
    }
    

    Output: i am wrapper class Integer (int is wrapped in Integer container)

    Now lets uncomment another overloaded method and see:

    public class Widening{
    public static void main(String[] args) throws Exception {
    int test = 20;
    myOverloadedFunction(test);
    }
    static void myOverloadedFunction(long parameter) {
    System.out.println("I am primitive long");
    }
    static void myOverloadedFunction(Integer parameter) {
    System.out.println("i am wrapper class Integer");
    }
    }
    

    Output: I am primitive long

    Compiler precedence is widening over autoboxing.

    Reference

提交回复
热议问题