Home Javatutorials Autoboxing unboxing in Java - Java Tutorials
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Autoboxing unboxing in Java - Java Tutorials

Advertisement
Autoboxing unboxing in Java

Autoboxing and Unboxing

The Autoboxing and Unboxing  was released with the Java 5.

Autoboxing

During assignment, the automatic transformation of primitive  type(int, float, double etc.) into their object equivalents or wrapper type(Integer, Float, Double,etc) is known as Autoboxing.

During assignment or calling of constructor, the automatic transformation of wrapper types into their primitive equivalent  is known as Unboxing.

Conversion of int into Integer

int inative = 0;

inative = new Integer(5); // auto-unboxing

Integer intObject = 5; // autoboxing

Storing int a into vector vt

int a = 10;

Vector <integer> vt = new Vector <integer> ();

vt.add(a);

int n = vt.elementAt(0); </integer></integer>

Autoboxing also works with comparison

int a = 10;

Integer b = 10;

System.out.println(a==b);

Output of the above code will be :

   Output :               
   true

EXAMPLE

Boxing/Unboxing of Character value :

public class MainClass {
public static void main(String args[]) {
Boolean booleanObject = true;

if (booleanObject){
System.out.println("b is true");
}

Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char

System.out.println("ch2 is " + ch2);
}
}

Output

  b is true                    
 ch2 is x
Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Ask Questions?    Discuss: Autoboxing Yourself in JDK 1.5- Java Tutorials  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
chotu
April 2, 2012
wat is the Autoboxing &un boxing

hi i m new for the java ... can u pls tellme wat is the Autoboxing &un boxing.......... and y should and where can we use this concepts..............?
siva kumar
July 30, 2012
AUTO BOXING

Is AUTO BOXING and AUTO UNBOXING will happen only when we are using collections??
DMCA.com