Saturday 14 July 2018

Autoboxing and Unboxing in java

Autoboxing and Unboxing
the Autoboxing and Unboxing was released with java 5.The automatic data conversion of primitive data types into equivalent wrapper type is known as boxing and opposite function called unboxing.Autoboxing and Unboxing have many advantage in java programming.
we give some java Autoboxing and Unboxing example here..

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);

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);
}
}

0 comments:

Post a Comment