WHAT'S NEW?

What is Widening?

Widening is a process that takes place while working with the concept of primitives in Java.



Let say you have a method which takes an int parameter, but while calling the argument passed was byte.
Here comes into the picture the concept of Widening.

When a method call is made and the matching parameters are not found they search for the other primitive they can be widened to.

The order of widening goes like this.

Now let us consider the following class,




MyClass.java


class MyClass
{
public void m1(int i)
{
System.out.println("int called");
}
public void m1(double d)
{
System.out.println("double called");
}
}





Demo.java


class Demo
{
public static void main(String[] args)
{
MyClass obj;
obj=new MyClass();

byte b=10;
short s=20;
float f=3.14f;
obj.m1(b);
obj.m1(s);
obj.m1(f);
}
}

Now here when the first call to the method was made with byte primitive object, it calls the int value.
Why?
When the call is made and if the matching parameters are not found they call the NEXT LARGEST SMALLEST VALUE from the list.
So here in our case when the byte is passed next available value according to the rule would be int, as our class have no method with parameter short,hence another value after that is int.
Now the same happens with short, no matching parameter hence it too get widened to int.
When float is executed it gets widened to double, as that is the next largest smallest value available.

0 comments:

Post a Comment