Autoboxing and Unboxing in java

Autoboxing and Unboxing in java:

Autoboxing: Converting primitive data type to wrapper class objects.
Eg: int to Integer, double to Double, float to Float etc..,
Unboxing: Converting wrapper class objects to primitive data types.
Eg: Integer to int, Double to double, Float to float etc..,

 

Autoboxing Example program:

import java.util.Vector;
public class Autoboxing {
public static void main(String[] args) {
// Autoboxing - Primitive data type to wrapper class objects.
// Eg: int to an Integer, a double to a Double, a float to a Float etc...
int i =10;
int j=20;
int k = 30;
Vector<Integer> myVect = new Vector<Integer>();
myVect.add(i); // i,j,k is actually int (primitive type) but autoboxed and added as Integer object in the vector.
myVect.add(j);
myVect.add(k);
System.out.println("Autoboxing (int to Integer)"+myVect.get(1));
}
}

Output:
Autoboxing (int to Integer)20

 

 

Unboxing Example Program:

public class Autoboxing {
public static void main(String[] args) {
// Unboxing - Wrapper class objects to primitive data type.
//Eg: Integer to a int, Double to a double, Float to a float etc...
Integer myIntegerFirst = new Integer(-350);
Integer myIntegerSecond = new Integer(405);
int myInt = Add(myIntegerFirst,myIntegerSecond); // myIntegerFirst and myIntegerSecond is actually Integer object but it is passed to Add method as int (primitive type) values.
System.out.println("Unboxing (Integer to int) "+myInt);
}

private static int Add(int myIntegerFirst, int myIntegerSecond) {
return myIntegerFirst+myIntegerSecond;
}
}

Output:
Unboxing (Integer to int) 55

 

 

158 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *