Repository navigation
Wrapper Classes
A wrapper class is a class that wraps (encloses) around a data type and gives it an object appearance. It is one of eight classes provided in the java.lang package to provide object methods for the eight primitive types. All of the primitive wrapper classes in Java are immutable.
- They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
- The classes in java.util package handles only objects and hence wrapper classes help in this case also.
- Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.
- An object is needed to support synchronization in multithreading.
- It has methods that support Object like creation from other types.. like String eg : Integer number2 = new Integer("55");//String
Using a Wrapper Class Constructor Like examples Integer number = new Integer(55);//int Integer number2 = new Integer("55");//String Float number3 = new Float(55.0);//double argument Float number4 = new Float(55.0f);//float argument Character c1 = new Character('C');//Only char constructor //Character c2 = new Character(124);//COMPILER ERROR Boolean b = new Boolean(true); //"true" "True" "tRUe" - all String Values give True //Anything else gives false Boolean b1 = new Boolean("true");//value stored - true Boolean b2 = new Boolean("True");//value stored - true Boolean b3 = new Boolean("False");//value stored - false Boolean b4 = new Boolean("SomeString");//value stored - false Float number5 = new Float("55.0f");//String
valueOf Static Methods
Provide another way of creating a Wrapper Object Integer hundred = Integer.valueOf("100");//100 is stored in variable Integer seven = Integer.valueOf("111", 2);//binary 111 is converted to 7
We should prefer static valueOf method, because it may save you some memory. Using the Constructor you will always create a new object, while using valueOf() static method, it may return you a cached value with-in a range. For example : The cached values for long are between [-128 to 127].
Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc. Auto Boxing helps in saving memory by reusing already created Wrapper objects. Auto Boxing uses the static valueOf methods. However wrapper classes created using new are not reused. Two wrapper objects created using new are not same object while two wrapper objects created using boxing will be same object.
Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc.