Pages

Friday, 20 May 2022

Wrapper Class


The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into corresponding objects. The eight primitive data types byte, short, int, long, float, double, char and boolean are not objects.
Why we need wrapper class in Java
one of the reason why we need wrapper is to use them in collections API. On the other hand the wrapper objects hold much more memory compared to primitive types. So use primitive types when you need efficiency and use wrapper class when you need objects instead of primitive types.
The primitive data types are not objects so they do not belong to any class. While storing in data structures which support only objects, it is required to convert the primitive type to object first which we can do by using wrapper classes.
 
Ex1: Converting a primitive type to Wrapper object public class JavaExample
{
public static void main(String args[])
{
//Converting int primitive into Integer object int num=100;
Integer obj=Integer.valueOf(num); System.out.println(num+ " "+ obj);
}
}
Output:
100 100
Ex2: Converting Wrapper class object to Primitive public class JavaExample
{
public static void main(String args[])
{
//Creating Wrapper class object Integer obj = new Integer(100);
//Converting the wrapper object to primitive int num = obj.intValue();
System.out.println(num+ " "+ obj);
}
}
Output:
100 100
Ex3: Primitive Types to Wrapper Objects class Main
{
public static void main(String[] args)
{
// create primitive types int a = 5;
double b = 5.65;
//converting primitive types into wrapper class objects Integer c=Integer.valueOf(a);
Double d=Double.valueOf(b);
 
if(c instanceof Integer)
{
System.out.println("c It is an instance/object of Integer.");
}
if(d instanceof Double)
{
System.out.println("d It is an instance/object of Double.");
}
}}
Output:
D:\>javac Main.java D:\>java Main
c It is an instance/object of Integer. d It is an instance/object of Double.
Ex4: Wrapper Objects into Primitive Types class Main
{
public static void main(String[] args)
{
// creates objects of wrapper class Integer aObj = Integer.valueOf(23); Double bObj = Double.valueOf(5.55); Float cObj=Float.valueOf(3.4f);
// converts into primitive types int a = aObj.intValue();
double b = bObj.doubleValue(); float c=cObj.floatValue();
System.out.println("The value of a: " + a); System.out.println("The value of b: " + b); System.out.println("The value of c: " + c);
}
}
Output
D:\>javac Main.java D:\>java Main
The value of a: 23 The value of b: 5.55 The value of c: 3.4
 

No comments:

Post a Comment

Servlet - JSP Programs

JSP(Java Server Pages) Programs : JavaServer Pages (JSP) is a Java standard technology that enables you to write dynamic data-driven pages f...