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";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.
Integer i = new Integer(str);
i = i-10;
System.out.println(i); //result is 90
Besides, we should be more careful when comparing wrapper class objects.
For example:
Character a=new Character('a');Reason:
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
- 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 Type | Size | Minimum Value | Maximum Value | Wrapper Type |
| char | 16-bit | Unicode 0 | Unicode 216-1 | Character |
| byte | 8-bit | -128 | +127 | Byte |
| short | 16-bit | -215 | +215-1 | Short |
| int | 32-bit | -231 | +231-1 | Integer |
| long | 64-bit | -263 | +263-1 | Long |
| float | 32-bit | 32-bit IEEE 754 floating-point numbers | Float | |
| double | 64-bit | 64-bit IEEE 754 floating-point numbers | Double | |
| boolean | 1-bit | true or false | Boolean | |


Good article :)
ReplyDeleteAnother article about primitive and wrapper
http://www.behindjava.com/2014/06/primitive-and-wrapper-classes-in-java.html