Wrapper class in Java

java wrapper class

Wrapper class in Java

According to Wikipedia “In object-oriented programming, a wrapper class is a class that encapsulates types, so that those types can be used to create object instances and methods in another class that needs those types. So a primitive wrapper class is a wrapper class that encapsulates hides or wraps data types from the eight primitive data so that these can be used to create instantiated objects with methods in another class or in other classes. The primitive wrapper classes are found in the Java API.”

The primitive data type must be converted to it’s corresponding wrapper class, because the object is necessary to modify the argument or parameter passed into the method.

Collection framework such ArrayList, Vector store only the objects, not primitive data types so it must be converted to its corresponding wrapper class.


It is a process by which we can convert primitive data types into object types.  Every primitive data type has its own wrapper class.
Primitive Type
Wrapper class
boolean
Boolean
char
Character
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double

All the wrapper class is the subclasses of the abstract number class.

Java data types are primitive by default and sometimes we require to represent as an object so we need to wrap the primitive data type in a class.

class WrapperClassExample
{
    public static void main(String[] args)
    {
        String a = "20";
        String b = "30";
        int f1, f2, result;
        System.out.println("Sum before:"+ a + b); // print 2030 not 50
        f1 = Integer.parseInt(a); // convert String to int type
        f2 = Integer.parseInt(b); // convert String to int type
        result = f1 + f2;
        System.out.println("sum after: " + result); // 50
    }
}

public class Example { 
  public static void main(String[] args) { 
    Integer intEx = 10
    Double doubleEx = 8.87
    Character charEx = 'C'
    System.out.println(intEx);
    System.out.println(doubleEx);
    System.out.println(charEx);
  }
}


Boxing-UnBoxing in Java is used to automatically convert the primitive data types into its corresponding objects.

Sample output
Sum before:2030
sum after: 50

In this program, we try to add a and b it will give 2030 not 50 because “20” and “30” are not integer type. So if need to sum it up then we need to convert String to int type.

Buy some important Computer Books Books 
Java: The Complete Reference by Herbert Schildt
Java: A Beginner's Guide, Sixth Edition by Herbert Schildt
DSSSB TGT, PGT COMPUTER SCIENCE GUIDE-CUM-PWB (E) - 1039 by Think Tank of Kiran Prakashan (Author)
UGC NET/JRF/SET Computer Science and Applications: Paper II & III by Chandresh Shah (Author), Saurab Mishra (Author)




SHARE THIS
Previous Post
Next Post