Thursday , November 21 2024

Wrapper class in Java

Wrapper classes are used to convert primitive into object and object into primitive. Each of Java’s eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they “wrap” the primitive data type into an object of that class.

The primitive data types are not objects, they do not belong to any class. they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language. For example, upto JDK1.4, the data structures accept only objects to store. A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.The Number class is part of the java.lang package.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.

Primitive data type Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Wrapper class Example: Primitive to Wrapper

public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);
}}
Output:

20 20 20

Wrapper class Example: Wrapper to Primitive

public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);
}}
Output:

3 3 3

 

 

About admin

Check Also

Arrays in java

The array is a data structure which stores a fixed-size sequential collection of elements of …

Leave a Reply