Wrapper class

Wrapper classes are object representation of primitive data types. For each primitive data type there is a Wrapper class in java.

Following reason behind to use wrapper classes.

1)As you know that all collections method accept only Object class for storing elements. You cann’t add primitive one to any of the collection.
2)Sometimes you need to convert numeric strings into numeric values which can be easily done by Wrapper classes.
3)Object representation of primitive data types.
4)As you know in java Object class is parent of each class by which we can pass any object to method parameter if reference type is Object class. So object representation help you a lot.

Wrapper Classes

 

Primitive Data TypeWrapper Class
byteByte
shortShort
intInteger
longLong
charCharacter
floatFloat
doubleDouble
booleanBoolean

All wrapper classes are final and immutable. No sub-classes can be created of wrapper one and no modification to wrapper object is allowed. All wrapper classes are extended abstract class Number except Character.

Method of Number Class

These all methods must be overided by their child classes.

  1. intValue()
  2. longValue()
  3. floatValue()
  4. doubleValue()
  5. byteValue()
  6. shortValue()

Common Methods of Wrapper classes

  1. XXX static parseXXX(String value) throws NumberFormatException
  2. XXX static valueOf(String value) throws NumberFormatException
  3. int intValue()
  4. long longValue()
  5. float floatValue()
  6. double doubleValue()
  7. byte byteValue()
  8. short shortValue()

Wrapper Class Example

 public class WrapperExample {
	public static void main(String[] args) {
	     //parsing from string
	      String num = "12"; 
	      String dec  = "10.2";
	      int n1   = Integer.parseInt(num); //converts string to int
	      Integer n2= Integer.parseInt(num);//converts string to Integer object
	      float f1 = Float.parseFloat(dec);//converts string to float
	      Float f2 = Float.parseFloat(dec);//converts string to Float Object
	      int n3  = f2.intValue();//returns the int value of 10.2 

	      //Creating object of wrapper by constructor
	      
	      Integer n4 = new Integer(10);
	      Integer n5 = new Integer("10");

	      System.out.println(n1);
	      System.out.println(n2);
	      System.out.println(f1);
	      System.out.println(f2);
	      System.out.println(n3);
	      System.out.println(n4);
	      System.out.println(n5);
	}
}

Output

12
12
10.2
10.2
10
10
10

Leave a Reply