Subscribe:

Thursday, February 2, 2012

Java Primitive Type and Wrapper Classes differences

 In this post, we will talk about the differences between primitive type and wrapper classes in Java.

Many people make mistakes when they are using the method of wrapper classes (Character, Integer) that are corresponding to some primitive types (char, int).



WRONG example:
(call a static method of Character class via char)
char a = 'a';
char capA = a.toUpperCase(a);

Why we need those wrapper classes such as Character, Integer, Long, etc?
When we need to convert String and numerical, we always use wrapper classes instead of primitive type. For example:
String str = "100";
Integer i = new Integer(str);
i = i-10;
System.out.println(i);    //result is 90
The drawback of using wrapper classes instead of primitive type is that wrapper classes will create more overhead and slow down the calculation a little bit.

Besides, we should be more careful when comparing wrapper class objects.
For example:
Character a=new Character('a');
Character bigA=new Character('A');
Character a2=new Character('a');
System.out.println("result a>A : "+(a>bigA));   //result is true
System.out.println("result a==a2 : "+(a==a2));  //result is false
System.out.println("result a==a2 : "+(a.equals(a2)));  //result is true
Reason:

  • a>bigA : The two objects are un-boxed to primitive type and compare, hence the result is true
  • a==a2 : The two objects are not un-boxed and compare as objects only. The references of two objects are different, hence the result is false.
  • a.equals.(a2) : the equals method compare the content of 2 objects instead of the references 


Below table lists the Primitive Type and the corresponding Wrapper class in Java:

Primitive TypeSizeMinimum ValueMaximum ValueWrapper Type
char16-bitUnicode 0Unicode 216-1Character
byte8-bit-128+127Byte
short16-bit-215+215-1Short
int32-bit-231+231-1Integer
long64-bit-263+263-1Long
float32-bit32-bit IEEE 754 floating-point numbersFloat
double64-bit64-bit IEEE 754 floating-point numbersDouble
boolean1-bittrue or falseBoolean

1 comment:

  1. Good article :)
    Another article about primitive and wrapper

    http://www.behindjava.com/2014/06/primitive-and-wrapper-classes-in-java.html

    ReplyDelete