WHAT'S NEW?

Widening vs Boxing

Widening vs Boxing is an interesting concept when it comes to the selection.



Let say there is a class with a method m1() which is overloaded , one version of the method takes an Integer parameter while other takes long parameter. Now if we make an int primitive and call the method, the calling method have two options, 



1. Either get boxed with Integer parameter.
2. Either get widened with long parameter.

So when you are stuck in such situation, always remember

Widening Beats Boxing.

class WhoCallWho
{

public void m1(Integer i)
{
System.out.println("Integer invoked");
}
public void m1(long l)
{
System.out.println("long invoked");
}

}

Demo.java

public class Demo
{
public static void main(String[] args)
{
WhoCallWho obj=new WhoCallWho();
int x=10;
obj.m1(x);
}
}



When the method is invoked it calls the long rather than calling Integer version of the method.

Probable reason why Widening beats Boxing is, the concept of Autoboxing was introduced in jdk 1.5, any application developed prior to that would have resulted in erratic behaviors , if Boxing was given preference over Widening.

0 comments:

Post a Comment