Home Javatutorials Autoboxing unboxing in Java - Java Tutorials



Autoboxing unboxing in Java - Java Tutorials
Posted on: April 18, 2011 at 12:00 AM
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

Related Tags for Autoboxing unboxing in Java - Java Tutorials:


More Tutorials from this section

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

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.