Wrapper Classes for Primitives

Generally when you need to deal with numbers, you choose one of the primitive classes. However when you try to keep a group of numbers in a Collection object, then you cannot use primitives as Collection framework only supports objects. To overcome this limitation, Java provides us with equivalent wrapper classes for each primitive. A wrapper numbers class is nothing but a class which encloses a primitive and behaves as an object instead of primitive.

Here are some of the wrapper classes for primitives which all extend the top level abstract Number class:

In addition to numbers, Java also provides a wrapper for boolean values:

Now you can create a collection of primitives using any of these wrapper classes.

While creating a wrapper object, you just assign the primitive value to the wrapper class's object reference. A wrapper object is created automatically. Converting primitive data types into object is called boxing. In a similar way, a primitive reference can get assigned with the primitive value when it is assigned a wrapper object. This process is called unboxing.

Here is an example

import java.util.ArrayList;
public class NumbersDemo{

    public static void main(String[] args){
        Integer a = 2; // boxing
        int b = a; //unboxing

        ArrayList<Integer> c = new ArrayList<Integer>();
        c.add(3); //boxing
        c.add(4); //boxing



2 4

Integer classes are also commonly used to get the primitive values from strings contains only primitive values. Here is an example:

public class ParseDemo{

    public static void main(String[] args){
        String a = "123";
        int b = Integer.parseInt(a);

        String c = "true";
        Boolean d = Boolean.parseBoolean(c);

Points to note

  • When ever you print out an object using the System.out.println statement, the compiler calls the toString() method of the Object class. The object class's toString() methods just prints the reference value of the variable. Many classes override the object classes toString() method and give their own meaningful implementation. All wrapper classes override the toString() method of the object. In the above example the toString() method on Integer class returns the string representation of the primitive type that it encloses.
  • If you try to parse a string which does not contain a primitive value, then it will result in a ParseException being thrown.

results matching ""

    No results matching ""