Java Autoboxing and Unboxing with examples

Primitive type	Wrapper class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double

When does the autoboxing and unboxing happens in Java


class AutoboxingExample1
public static void myMethod(Integer num){
public static void main(String[] args) {
/* passed int (primitive type), it would be
* converted to Integer object at Runtime
Integer inum = 3; //Assigning int to Integer: Autoboxing
Long lnum = 32L; //Assigning long to Long: Autoboxing
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(11); //Autoboxing - int primitive to Integer
arrayList.add(22); //Autoboxing


class UnboxingExample1
public static void myMethod(int num){
public static void main(String[] args) {

Integer inum = new Integer(100);

/* passed Integer wrapper class object, it
* would be converted to int primitive type
* at Runtime
Integer inum = new Integer(5);
int num = inum; //unboxing object to primitive conversion
ArrayList arrayList = new ArrayList()
int num = arrayList.get(0); // unboxing because get method returns an Integer object

What happens behind the scenes?

Integer number = 100;
Integer number = Integer.valueOf(100);
Integer num2 = new Integer(50);
int inum = num2;
Integer num2 = new Integer(50);
int inum = num2.intValue();

Few things you should take care:




digital marketer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

3 labs to help you master online collaboration tools

When not to use agile

An image showing when to use sequential or agile methods depending on whether scope is fixed or estimated.

CS371p Blog: Week 6

Module Oriented Architecture — Part 1: Coupling and Decoupling

Download In !PDF 101 Labs — CompTIA Network+ Read

In-depth Analysis of Time: Flink Advanced Tutorials

Set up your own web server for free!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
sindhuja cynixit

sindhuja cynixit

digital marketer

More from Medium

Java: Using Array to Create a Stack Class

How To Learn Java in 2022: Ultimate Java Tutorial For Beginners

[Solved]: Eclipse JUnit Error: Class not found java. java.lang.ClassNotFoundException…

A Quick Introduction to Writing Purr-fect Unit Tests