Pages

Saturday 5 October 2019

Wrapper classes

Agenda
  • Wrapper classes
  • The class hierarchy of wrapper class
  • Creating an object of the wrapper classes
Wrapper classes
  • The wrapper classes are used to wrap primitives in an object. So, they can be added to a collection object.
  • To define utility functions that are required for the primitives.
  • All wrapper classes are immutable.
  • Wrapper classes Byte, Short, Integer and Long cache objects with values in the range of -128 to 127. The Character class caches objects with values 0 to 127.
  • Wrapper classes Float and Double don't cache objects for any range of values.
Example:
  1. public class Test{
  2. public static void main(String[] args){
  3. Integer a =10;
  4. Integer b=10;
  5. System.out.println(a==b);//true
  6. Integer c=128;
  7. Integer  d =128;
  8. System.out.println(c==d);//false,reason value 128 is out of range of cache objects .So it will create new object.
  9. }
  10. }
Creating object of the wrapper classes
You can create objects of all the wrapper classes in multiple ways
Assignment : By assigning a primitive to a wrapper class variable(Auto-boxing)
Ex: Integer a =10;
Constructor: By using wrapper class constructors.
Ex: Integer a = new Integer(10);
Static methods: By calling static method of wrapper classes, like valueOf();
Ex: Integer wrapper = Integer.valueOf(10);

Wrapper Classes Constructors
Wrapper Class
Constructors
Byte
Byte(byte a),Byte(String s)
Short
Short(short a),Short(String s)
Integer
Integer(int a),Integer(String s)
Long
Long(long a),Long(String s)
Float
Float(float a),Float(String s)
Double
Double(double a),Double(String s)
Character
Character(char a)
Boolean
Boolean(boolean a),Boolean(String s)

Note: Wrapper class Character has no String argument constructor.
The class hierarchy of wrapper class




Conversion of Wrapper Classes to String and Primitive and Vice-Versa
String to Wrapper Class:
Integer wrapper= Integer.valueOf("10");

String to Primitive:
 int primitive = Integer.parseInt("10");

Wrapper to String:
String String1= String.valueOf(wrapper);
String String2 = wrapper.toString();

Wrapper to primitive:
int intValue = wrapper.intValue();

Primitive to Wrapper:
Integer wrapper = Integer.valueOf(10);

Primitive to String:
String string3 = Integer.toString(10);

Summary of above conversion in Diagram