Primitive Wrapper Types

Primitive Wrapper Types

This topic will talk about what is wrapper types, boxing, unboxing and autoboxing.

A wrapper type is a class that encapsulates types.

  • boolean => Boolean
  • byte => Byte
  • short => Short
  • int = Integer
  • long => Long
  • float => Float
  • double => Double
  • char => Character

Integer

int primitive cannot hold null value, but since Integer wrapper is a object, so it can hold null value.

public static void main(String args[]) 
{ 
   int value = 1;
   Integer nullInt = null;
}

Initialize

When declare Integer as static or private variable without initialize will default to null. While local variable must declare and initialize.

static Integer z;

public static void main(String args[]) 
 { 
    Integer a = new Integer(100);
    Integer b = 100;
    Integer c = Integer.valueOf(100);
    Integer d = Integer.parseInt("100");
    Integer e;
    //System.out.print(e.doubleValue()); this will not compile
 }

Boxing

In a nutshell, boxing mean putting primitive type value into primitive wrapper. If you declare the integer like this way, your eclipse editor shall show you that syntax is deprecated since version 9.

Integer a = new Integer(100);


The constructor Integer(int) is deprecated since version 9

Integer value = Integer.valueOf(100);

UnBoxing

Unboxing is opposite of boxing, which is converting primitive wrapper to primitive type. Eg:

int value = Integer.valueOf(100);

AutoBoxing

The process of conversion primitive type to their corresponding primitive wrapper is call autoboxing

Integer value = 10;

totalUp( 1, 2); // autoboxing

private void totalUp( Integer a, Integer b)
{
Integer total = a + b;
System.out.print(“Total = ” + total);
}

autoboxing convert primitive to primitive wrapper

Nullpointer Exception

Due to primitive wrapper can hold null value, be careful when it unboxing and get throws null pointer exception. Eg

Integer nullInt = null;   
int value = nullInt;
System.out.println(value); // throws null pointer exception, primitive cannot contain null

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.