What is the need of wrapper classes in Java?

Java 8Object Oriented ProgrammingProgramming

In java.lang package you can find a set of classes which wraps a primitive variable with in their object these are known as wrapper classes. Following is the list of primitive datatypes and their respective classes −

Primitive datatypeWrapper class
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean

Example

 Live Demo

public class Sample {
   public static void main (String args[]){
      Integer obj = new Integer("2526");
      int i = obj.intValue();
      System.out.println(i);
   }
}

Output

2526

Need for wrapper classes in Java

Java provides primitive datatypes (char, byte, short, int, long, float, double, boolean) and, reference types to store values.

  • Whenever we pass primitive datatypes to a method the value of those will be passed instead of the reference therefore you cannot modify the arguments we pass to the methods. In this scenario you can use objects of such variables.
  • Classes in certain packages like util handles only objects.
  • Collection types such as ArrayList, Vectors etc. stores only objects (not primitive datatypes).
  • Your data need to be an objects for synchronization, serialization and, multithreading.

Therefore, at times we need to have primitive datatypes in the form of objects. At such scenarios you can use wrapper classes.

raja
Published on 05-Jul-2019 07:26:13
Advertisements