Java | Wrapper Class

05 min read

Wrapper Class:

  • Defined in java.lang package.
  • Primitive data type, although not implemented as objects, for performance considerations, their corresponding object representations are needed for the following reason:

There are collection classes that deal only with only objects. So, to store a primitive data type in one of these classes, we need to wrap the primitive type in a class.

  • Thus, for all the 8 primitive data types in Java, equivalent Wrapper Classes are there.

Note that the class names start with capital letter. Except for Boolean & Character, all other classes are subclasses of an abstract class called 'Number'.

To build an object for a given primitive data type, all these classes have appropriate constructors defined. There are 2 types of constructors for all the classes except character.

 

1. Constructor — I

  • Takes the corresponding type of numeric or boolean (for Boolean class) values as arguments and creates the object.

Double dd = new Doble(double);

Float ff = new Float(float);

Short ss = new Short(short);

Long ll = new Long(long);

Integer ii= new Integer(int);

Byte bb = new Byte(byte);

Boolean bool = new Boolean(boolean);

Example:

1. Integer I = new lnteger( 10);

Now 'i' is a reference to the object containing the integer value 10.

2. Double d 1 = new Double(10.41);

Double d2 = new Doublet 10.4);

3. Boolean bool = new Boolean(true);

 

2. Constructor - II

  • It constructs the object from the string representation of a numeric data or boolean data.

Double dd new Doubler 110.5");

Long ll = new Long(" 1 50678924");

Byte bb = new Byte(args [0]);

If "100" is given as the command line argument, which is in the form of a String, it can be converted to an object.

Data type

Wrapper Class
  • boolean
  • byte
  • char
  • short
  • int
  • long
  • float
  • double
  • Boolean
  • Byte
  • Character
  • Short
  • Integer
  • Long
  • Float
  • Double
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error