HudaTutorials.com

Java Wrapper Classes - Wrapper Classes in Java

Last updated on

Wrapper Classes in Java

Java Wrapper classes wrap the values of the primitive data type into objects. In other words the Java wrapper classes create objects for primitive data types. The Java wrapper classes are Boolean, Byte, Character, Short, Integer, Float, Long and Double.

For example an object of type Double, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. Java Wrapper classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode.

The following Java Wrapper Classes table shows which wrapper class is for which primitive data type.

Wrapper Class Primitive Data Type
Boolean boolean
Byte byte
Character char
Short short
Integer int
Float float
Long long
Double double

Advantages of Java Wrapper Classes

  1. Java Wrapper Classes convert primitive data type into Object data type.
  2. Java Wrapper Classes are very helpful in Java Collection Framework. Because most of the Java collection classes accepts object data type.
  3. Java Wrapper Classes needed to use the classes of java.util package.

What is the Autoboxing in Java?

Automatic conversion of primitive data type to the object data type with corresponding Java wrapper class is called as Autoboxing.

For example convert primitive data type int to Java wrapper class Integer.

Java Autoboxing example

/*  Java Autoboxing example convert primitive data type int
    to Java wrapper class Integer
    Save with file name AutoboxingExample.java  */
import java.util.ArrayList;
public class AutoboxingExample
{
	public static void main(String args[])
	{
		int intval = 100;
		// AUTOBOXING
		// AUTOMATIC CONVERSION FROM PRIMITIVE DATA TYPE TO WRAPPER CLASS OBJECT
		Integer intobj = intval;
		System.out.println("Autoboxing Value : "+intobj);
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		// AUTOBOXING BECAUSE ARRAYLIST STORES OBJECTS ONLY
		arrayList.add(101);
		System.out.println(arrayList.get(0));
	}
}

What is the Unboxing in Java?

Automatic conversion of Java wrapper class object to the primitive data type is called as Unboxing.

For example convert Java wrapper class Integer to primitive data type int.

Java Unboxing example

/*  Java Unboxing example convert Java wrapper class Integer
    to primitive data type int
    Save with file name UnboxingExample.java  */
import java.util.ArrayList;
public class UnboxingExample
{
	public static void main(String args[])
	{
		Integer intobj = new Integer(100);
		// UNBOXING
		// AUTOMATIC CONVERSION FROM WRAPPER CLASS OBJECT TO PRIMITIVE DATA TYPE
		int intval = intobj;
		System.out.println("Unboxing Value : "+intval);
	}
}