Java-Autoboxing on Methods

Autoboxing on Methods

In addition to the simple case of assignments, autoboxing automatically occurs whenever a primitive type must be converted into an object; auto-unboxing takes place whenever an object must be converted into a primitive type. Thus, autoboxing/unboxing might occur when an argument is passed to a method, or when a value is returned by a method.

In the program, notice that antoUnBox( ) specifies an Integer parameter and returns an int result. Inside main( ), antoUnBox( ) is passed the value 40. Because antoUnBox( ) is expecting an Integer, this value is automatically boxed. Then, antoUnBox( ) returns the int equivalent of its argument. This causes in to be auto-unboxed. Next, this int value is assigned to data1 in main( ), which causes the int return value to be autoboxed.

Program

0

Program Source

public class Javaapp {

    static Integer autoBox(int in)
    {
        return in;
    }
    
    static int antoUnBox(Integer in)
    {
        return in;
    }
    
    public static void main(String[] args) {
        
        Integer data1 = autoBox(20);
        int data2 = antoUnBox(40);
        System.out.println("data1 = "+data1);
        System.out.println("data2 = "+data2);
    }
}

Leave a Comment