Wherever possible try to use Primitive types instead of Wrapper classes
Not everything in Java is an object. There is a special group of data types (also known as primitive types) that will be used quite often in your programming. For performance reasons, the designers of the Java language decided to include these primitive types.
Creating an object using new isn’t very efficient because new will place objects on the heap. This approach would be very costly for small and simple variables. Instead of create variables using new, Java can use primitive types to create automatic variables that are not references. The variables hold the value, and it’s place on the stack so its much more efficient.
Java determines the size of each primitive type. These sizes do not change from one machine architecture to another (as do in most other languages). This is one of the key features of the language that makes Java so portable.
Take note that all numeric types are signed. (No unsigned types).
Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas Wrapper classes are stores information about complete class.
Sometimes a programmer may add bug in the code by using wrapper due to oversight. For example, in below example:
int x = 10; int y = 10; Integer x1 = new Integer(10); Integer y1 = new Integer(10); System.out.println(x == y); System.out.println(x1 == y1);
The first Println will print true whereas the second one will print false. The problem is when comparing two wrapper class objects we cant use == operator. It will compare the reference of object and not its actual value.
Also if you are using a wrapper class object then never forget to initialize it to a default value. As by default all wrapper class objects are initialized to null
.
Boolean flag; if(flag == true) { System.out.println("Flag is set"); } else { System.out.println("Flag is not set"); }
The above code will give a NullPointerException
as it tries to box the values before comparing with true and as its null.