Wrapper class in Java

Wrapper class in java are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion between primitive types and their corresponding wrapper classes in java programs.

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.

The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes.

Primitive TypeWrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
Example: Primitive to Wrapper
public class WrapperExample1 { public static void main(String args[]) { //Converting int into Integer int a=31; Integer i=Integer.valueOf(a);//converting int into Integer Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally System.out.println(a+" "+i+" "+j); } }


Output:
31 31 31
Example: Wrapper to Primitive
public class WrapperExample2{ public static void main(String args[]){ //Converting Integer to int Integer a=new Integer(5); int i=a.intValue();//converting Integer to int int j=a;//unboxing, now compiler will write a.intValue() internally System.out.println(a+" "+i+" "+j); }}


Output:
5 5 5
Why do we need wrapper classes?

I think it was a smart decision to keep primitive types and Wrapper classes separate to keep things simple. We need wrapper classes when we need a type that will fit in the Object world programming like Collection classes. We use primitive types when we want things to be simple.

Primitive types can’t be null but wrapper classes can be null.

Wrapper classes can be used to achieve polymorphism.

Here is a simple program showing different aspects of wrapper classes in java.

Another Example: Wrapper classes
package com.journaldev.misc; import java.util.ArrayList; import java.util.List; public class WrapperClasses { private static void doSomething(Object obj){ } public static void main(String args[]){ int i = 10; char c = 'a'; //primitives are simple to use int j = i+3; //polymorphism achieved by Wrapper classes, we can't pass primitive here doSomething(new Character(c)); List list = new ArrayList(); //wrapper classes can be used in Collections Integer in = new Integer(i); list.add(in); //autoboxing takes care of primitive to wrapper class conversion list.add(j); //wrapper classes can be null in = null; } }





Instagram