Boxing and Widening

2020-02-25 22:53发布

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 be done or widening should be done?

标签: java boxing
7条回答
干净又极端
2楼-- · 2020-02-25 23:45

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

查看更多
登录 后发表回答