Java | Autoboxing and Auto-Unboxing

05 min read

Autoboxing:

Converting a primitive type into the object of the corresponding wrapper class, automatically.

The Java compiler applies autoboxing when a primitive type is

  1. Passed as a parameter to a method that expects an object of the corresponding wrapper class
  2. Assigned to a variable of the corresponding wrapper class

Examples:

1) Integer iob=100;

iob--> Object of Integer class         100 ---> primitive type data

The compiler auto boxes the primitive type integer value '100' into an Integer object, so that it can be assigned to the object 'iob'.

2)

class wrapper
{
void display(Integer ii)
{
System.out.println(ii);
}

public static void main(String[] args)
{
wrapper.display( I00);  ---> An integer is passed but the parameter in the method signature is an Integer object.
int j=2.5;
wrapper.display(j);
}

Thus integer value '100' and integer variable 'j' will be automatically converted, into the Integer object and so will compile successfully.

Note: In both the scenarios, auto-unboxing invokes the valueOf( ) method, for doing this conversion.

 

Auto-Unboxing:

Converting an object of wrapper type to its corresponding primitive value, automatically.

Unboxing is done during the following situations:

  1. When an object is passed as a parameter to a method which expects a primitive type value.
  2. When an object is assigned to a variable of the primitive type.

(eg) Integer iob = Integer.value0f(50);

int i = iob; ---> 'lob' is an object of Integer class. When it is assigned to an integer variable, it is unboxed to primitive data type, before getting assigned to the variable.

XXX Value( ) method is used implicitly when auto-unboxing takes place. (intValue( ), floatValue( ), shortValue( ), etc). Use of the wrappers should be restricted to only those cases in which object representations of a primitive type is required, in spite of having autoboxing/auto-unboxing facility.

 

Difference between parse XXX( ) & valueOf( ) methods:

parseXXX( ) : Returns a primitive data from the given string. eg: int x = Integer.parseInt("10);

valueOf( ) : Returns an object from a primitive type data or a string representation of the data. Integer ii= Integer.valueOf("10");

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error