Autoboxing and Unboxing Java Example

This post introduces about autoboxing and unboxing java example. Autoboxing and unboxing lets developers write cleaner code, making it easier to read. Because this technique let us use primitive types and Wrapper class objects together and no need to care about typecasting explicitly. Let’s discover now.

Autoboxing and Unboxing Java Example

Autoboxing in Java

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

Here is the simplest example of autoboxing:

In the above, Java will do autoboxing of char ‘x’ and return object of a Character wrapper class.

We consider the another example:

Although, you add the int values as primitive types, rather than Integer objects, to list. Finally you still get the list of Integer objects. Actually, Java compiler help you to convert from int values to Integer values by invoking the valueOf method

Here is the full java autoboxing example:

The Java compiler applies autoboxing when a primitive value is:

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

Unboxing in Java

Converting an object of a wrapper type to its corresponding primitive  value is called unboxing.

Consider the example below:

You know that the remainder (%) and unary plus (+=) operators do not apply to Integer objects. So Java compiler help you to convert an Integer to an int by invoking the intValue method at runtime.

Here is the full java unboxing example

The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Conclusion

The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing:

Autoboxing and Unboxing Java Example

That’s all about Autoboxing and Unboxing Java Example. Another post that you may interest in Java Autoboxing Performance Impact

References

Autoboxing in Java

 

Please share it if you found this useful
Hide Buttons