Wednesday, June 7, 2017

Wrapper class best practices for performance in Java

wrapper class wraps(encloses) around a data type (can be any primitive data type such as int, char, byte, long) and makes it an object.
Here are a few reasons why wrapper classes are needed:
  1. Allows null values.
  2. Can be used in collection such as ListMap, etc.
  3. Can be used in methods which accepts arguments of Object type.
  4. Can be created like Objects using new ClassName() like other objects:
    Integer wrapperInt = new Integer("10");
  5. Makes available all the functions that Object class has such as clone()equals()hashCode()toString() etc.
Wrapper classes can be created in two ways:
  1. Using constructor:
    Integer i = new Integer("1"); //new object is created
  2. Using valueOf() static operators:
     Integer i  = Integer.valueOf("100"); //100 is stored in variable
It is advised to use the second way of creating wrapper classes as it takes less memory as a new object is not created.

No comments:

Post a Comment