WRAPPER CLASS IN JAVA



A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store a primitive data types.

In other words, we can wrap a primitive value into a wrapper class object.

Need of Wrapper Classes

1.     They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).

2.     The classes in java.util package handles only objects and hence wrapper classes help in this case also.

3.     Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.

4.     An object is needed to support synchronization in multithreading.

For example: While working with collections in Java, we use  generics for type safety like this: ArrayList<Integer> instead of this ArrayList<int>. The Integer is a wrapper class of int primitive type. We use wrapper class in this case because generics needs objects not primitives.

5.     The primitive data types are not objects so they do not belong to any class. While storing in data structures which support only objects, it is required to convert the primitive type to object first which we can do by using wrapper classes.

6.     Wrapper class objects allow null values while primitive data type doesn’t allow it.

Reason for point 6:
·        Because null is a reference. And primitive types are not reference types. Only objects are reference types.

·        In Java programming, null can be assigned to any variable of a reference type (that is, a non-primitive type) to indicate that the variable does not refer to any object or array.

·        A null value thus indicates an unset reference (i.e. a reference to nothing).

·        null is a reference type and its value is the only reference value which doesn't refer to any object. Therefore there is no representation of null in memory.

The eight primitive data types byte, short, int, long, float, double, char and boolean are not objects. 

Wrapper classes are used for converting primitive data types into objects, like int to Integer etc.

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

Example 1: Converting a primitive type to Wrapper object
public class JavaExample{ 
   public static void main(String args[]){ 
            //Converting int primitive into Integer object 
            int num=100;  
            Integer obj=Integer.valueOf(num); 
            System.out.println(num+ " "+ obj); 
   }
}

Output: 100 100

As you can see both primitive data type and object have same values. You can use obj in place of num wherever you need to pass the value of num as an object.

Example 2: Converting Wrapper class object to Primitive
public class JavaExample{
   public static void main(String args[]){ 
            //Creating Wrapper class object
            Integer obj = new Integer(100); 
            //Converting the wrapper object to primitive
            int num = obj.intValue();
            System.out.println(num+ " "+ obj); 
   }
}

Output: 100 100

JAVA AUTOBOXING AND UNBOXING WITH EXAMPLES

Java 1.5 introduced a special feature of auto conversion of primitive types to the corresponding Wrapper class and vice versa.
AUTOBOXING: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

UNBOXING: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double etc.

AUTOBOXING

Lets see few cases with examples, where autoboxing happens.

Case 1: When a method is expecting a wrapper class object but the value that is passed as parameter is a primitive type. For example in the below code, the method myMethod() is expecting an object of Integer wrapper class, however we passed a primitive int type. The program ran fine as compiler does the autoboxing (conversion of int to Integer)

class AutoboxingExample1
{
   public static void myMethod(Integer num){
            System.out.println(num);
   }
   public static void main(String[] args) {
       /* passed int (primitive type), it would be
        * converted to Integer object at Runtime
        */
            myMethod(2);
   }
}

Output: 2

Case 2: When at some point of time, you are assigning a primitive type value to an object of its wrapper class. For example: The below statements are valid because compiler does the autoboxing at runtime.

Integer inum = 3; //Assigning int to Integer: Autoboxing
Long lnum = 32L; //Assigning long to Long: Autoboxing

Case 3: When dealing with collection framework classes:

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(11); //Autoboxing - int primitive to Integer
arrayList.add(22); //Autoboxing

Here ArrayList class is expecting an Integer wrapper class object but we are providing int primitive.

UNBOXING

Case 1: Method is expecting Integer object (parameter) but we have supplied int. Auotmatic conversion(unboxing) happened that converted Integer to int.

class UnboxingExample1
{
   public static void myMethod(int num){
            System.out.println(num);
   }
   public static void main(String[] args) {
           
            Integer inum = new Integer(100);
        /* passed Integer wrapper class object, it
         * would be converted to int primitive type
         * at Runtime
         */
            myMethod(inum);
    }
}

Output: 100

Case 2: Assignments

Integer inum = new Integer(5);
int num = inum; //unboxing object to primitive conversion

Case 3: While dealing with collection classes:

ArrayList arrayList = new ArrayList()
int num = arrayList.get(0); // unboxing because get method returns an Integer object

WHAT HAPPENS BEHIND THE SCENES?

In the above section we learnt how java compiler performs automatic conversion between primitive type and corresponding Wrapper objects. Lets discuss what compiler actually does during autoboxing and unboxing. The best way to understand this is to compare things before java 1.5 and after java 1.5 (boxing and unboxing introduced in java 1.5).

Autoboxing:

What we see:
Integer number = 100;

What compiler does (or what we used to do before java 1.5):
Integer number = Integer.valueOf(100);

Unboxing:

What we see:
Integer num2 = new Integer(50);
int inum = num2;

What compiler does:
Integer num2 = new Integer(50);
int inum = num2.intValue();

Similar things happen with the other wrapper classes and primitive types such as long, double, short etc.

EXAMPLES 1:
class TestDemo
{
          public static void main(String args[])
{
                   Byte a=10,b=20;
                   byte c=(byte)(a+b);
                   System.out.println(“value : ”+c);
}
}

EXAMPLES 2:
class Test
{
          public void m1(Integer x)
          {
                   System.out.println(“m1-called”);
}
}
class TestDemo
{
          public static void main(String args[])
{
Test obj=new Test();
obj.m1(null);
}       
}

Example 3:
class TestDemo
{
          public static void main(String args[])
{
                   String q=”3.14f”;
                   float value=Float.parseFloat(q);
                   System.out.println(“value : ”+value);
}
}

Example 4:
Class TestDemo
{
          public static void main(String args[])
          {
          try
          {
int i,sum=0;
for(i=0;i<args.length;i++)
{
sum=sum+Integer.parseInt(args[i]);
System.out.println(“value : ”+args[i]);
                             }
System.out.println(“sum : ”+sum);
}
catch(NumberFormatException e)
{
          System.out.println(“Please Enter Integer”);
}
}
}

Example 5:import java.util.Scanner;

public class WrapperDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Mobile Number");
        String mobile = sc.next();
        mobile = mobile.trim();
        boolean status = true;
        if(mobile.length()!=10)
            System.out.println("Invalid Mobile Number");
        else
        {
          for(int i=0; i<mobile.length(); i++)
          {
             char ch = mobile.charAt(i);
             if(Character.isDigit(ch) == false)
             {
               status = false;
               break;
             }
          }
          if(status)
              System.out.println("Valid Mobile Number");
          else
             System.out.println("Invalid Mobile Number");
        }
    }
}

Example 6:import java.util.Scanner;
public class TestValidateMobile {
  public static void main(String[] args) {
     System.out.println("Enter Mobile Number");
     String mobile = new Scanner(System.in).next();
     mobile = mobile.trim();
     if(mobile.length()==10)
     {
       try{
          Long.parseLong(mobile);
          System.out.println("Valid Mobile Number");
       }
       catch(Exception e)
       {
          System.out.println("Invalid Mobile Number..");
       }
     }
     else
       System.out.println("Invalid Mobile Number");
  }
}

Example 7:import java.util.Scanner;
public class TestValidation {
  public static void validateName(String name)
  {
      boolean status = true;
      for(int i=0; i<name.length(); i++)
      {
        char ch = name.charAt(i);
        if(!Character.isAlphabetic(ch))
        {
           status = false;
           break;
        }
      }
      String result = status ? "Valid Name" : "Invalid Name" ;
      System.out.println(result);
  }
  public static void validateMobile(String mobile)
  {
      try{
        Long.parseLong(mobile);
        if(mobile.length()!=10)
        {
          System.out.println("Mobile length must be 10");
        }
        else
         System.out.println("Valid Mobile Number");
      }
      catch(NumberFormatException e)
      {
         System.out.println("Only Digit Allowed");
      }
  }

  public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter Name");
      String name = sc.nextLine();
      System.out.println("Enter Your Mobile");
      String mobile = sc.next();
      TestValidation.validateMobile(mobile);
      TestValidation.validateName(name);
  }
}

Example 8:public class WrapperDemo {
  public static void main(String[] args) {
    char ch = 'A';
    System.out.println("IsUppercase : "+Character.isUpperCase(ch));
    System.out.println("IsLowerCase : "+Character.isLowerCase(ch));
    System.out.println("IsSpace:"+Character.isSpace(ch));
    System.out.println("IsDigit: "+Character.isDigit(ch));
    System.out.println("IsAlphabetic :"+Character.isAlphabetic(ch));
  }
}

Example 9:import java.util.Scanner;
public class WrapperDemo {
  public static void main(String[] args) {
    Scanner sc  =new Scanner(System.in);
    System.out.println("Enter First Name");
    String name = sc.next();
    name = name.trim();
    boolean status = false;
    for(int i=0; i<name.length(); i++)
    {
      char ch = name.charAt(i);
      if(Character.isAlphabetic(ch)==false)
      {
         status = true;
         break;
      }
    }
    if(status)
     System.out.println("Invalid Name");
    else
     System.out.println("Valid Name");
  }
}

Utility methods of Wrapper classes
The objective of Wrapper class is to define several utility methods which are required for the primitive types. There are 4 utility methods for primitive type which is defined by Wrapper class:

a) valueOf()
b) xxxValue()
c) parseXxx()
d) toString()

valueOf() method : We can use valueOf() method to create Wrapper object for given primitive or String.

syntax : public static Wrapper valueOf(String s);

// Java program to illustrate valueof()

class GFG {
    public static void main(String[] args)
    {
        Integer I = Integer.valueOf("10");
        System.out.println(I);
        Double D = Double.valueOf("10.0");
        System.out.println(D);
        Boolean B = Boolean.valueOf("true");
        System.out.println(B);
        // Here we will get RuntimeException
        Integer I1 = Integer.valueOf("ten");
    }
}
Output:

10
10.0
true
Exception in thread "main" java.lang.NumberFormatException: For input string: "ten"

Wrapper valueOf(primitive p) : Every Wrapper class including Character class contains the following method to create a Wrapper object for the given primitive type.

Syntax:public static Wrapper valueOf(primitive p);

// Java program to illustrate valueof()

class GFG {
    public static void main(String[] args)
    {
        Integer I = Integer.valueOf(10);
        Double D = Double.valueOf(10.5);
        Character C = Character.valueOf('a');
        System.out.println(I);
        System.out.println(D);
        System.out.println(C);
    }
}
Output:

10
10.5
a

xxxValue() method: We can use xxxValue() methods to get the primitive for the given Wrapper Object. Every number type Wrapper class( Byte, Short, Integer, Long, Float, Double) contains the following 6 methods to get primitive for the given Wrapper object:

public byte byteValue()
public short shortValue()
public int intValue()
public long longValue()
public float floatValue()
public float doubleValue()

// Java program to illustrate bytevalue()

class GFG {
    public static void main(String[] args)
    {
        Integer I = new Integer(130);
        System.out.println(I.byteValue());
        System.out.println(I.shortValue());
        System.out.println(I.intValue());
        System.out.println(I.longValue());
        System.out.println(I.floatValue());
        System.out.println(I.doubleValue());
    }
}
Output:

-126
130
130
130
130.0
130.0

parseXxx() method : We can use parseXxx() methods to convert String to primitive.
Syntax: public static primitive parseXxx(String s);

// Java program to illustrate parseXxx()

class GFG {
    public static void main(String[] args)
    {
        int i = Integer.parseInt("10");
        double d = Double.parseDouble("10.5");
        boolean b = Boolean.parseBoolean("true");
        System.out.println(i);
        System.out.println(d);
        System.out.println(b);
    }
}
Output:

10
10.5
true

toString() method:We can use toString() method to convert Wrapper object or primitive to String.

public String toString() : Every wrapper class contains the following toString() method to convert Wrapper Object to String type.

Syntax:public String toString();

// Java program to illustrate toString()

class GFG {
    public static void main(String[] args)
    {
        Integer I = new Integer(10);
        String s = I.toString();
        System.out.println(s);
    }
}
Output:

10

toString(primitive p) : Every Wrapper class including Character class contains the following static toString() method to convert primitive to String.

Syntax:public static String toString(primitive p);

// Java program to illustrate toString()

class GFG {
    public static void main(String[] args)
    {
        String s = Integer.toString(10);
        System.out.println(s);
        String s1 = Character.toString('a');
        System.out.println(s1);
    }
}
Output:

10
a


Comments