Autoboxing in Java

Ads
 

Autoboxing in Java

Autoboxing in Java is the automatic transformation of primitive data types ((int, float, double) into their corresponding Wrapper class object (Integer, Float, Double) by Java compiler.

Autoboxing in Java is the automatic transformation of primitive data types ((int, float, double) into their corresponding Wrapper class object (Integer, Float, Double) by Java compiler.

Autoboxing in Java is the automatic transformation of primitive data types ((int, float, double) into their corresponding Wrapper class object (Integer, Float, Double) by Java compiler.

One must also know about Unboxing, which means he automatic transformation of wrapper class object into their corresponding primitive data types.

Autoboxing or automatic transformation of primitive data types into Wrapper class by Java compiler takes place when:

  • a primitive data type is passed in a parameter of method, which is expecting an object of corresponding wrapper class
  • a primitive data type is assigned to a variable of the corresponding wrapper class.
Primitive data type Wrapper class
boolean Boolean
int Integer
char Character
float Float
double Double
byte Byte
long Long
short Short

Following is the example of Autoboxing in Java:

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

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

Integer i = 'x'; // box a int
int i2 = i; // unbox a int

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

Output:

a is true
i2 is x

Ads

Ads