An Introduction To Wrapper Classes

Posted By : Lakshmi Singh | 29-Oct-2021

Vectors cannot handle primitive data types like int, float, long, char  double. Primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package.

 

 

Simple Type Wrapper Class
boolean Boolean
char Char
double Double
float Float
int Int
long Long

 

The wrapper classes have number of unique methods for handling primitive data types and objects. 

 

1. Converting primitive numbers to object number using contructor methods

 

Constructor Calling Conversion Action
Integer IntVal = new Integer(i); Primitive Integer to Integer object
Float FloatVal = new Float(f); Primitive Float to Float object
Double DoubleVal = new Double(d); Primitive Double to Double object
Long LongVal = new Long(l); Primitive Long to Long object

 

 

2. Converting object numbers to primitive numbers using typeValue() method

 

Method Calling Conversion Action
int i = val.intValue(); Object to primitive integer
float f = val.floatValue(); Object to primitive float
long l = val.longValue(); Object to primitive long
double d = val.doubleValue(); Object to primitive double

 

 

3. Converting numbers to strings using toString() method

 

Method Calling  Conversion Action
str = Integer.toString(i); Primitive integer to string
str =Float.toString(f); Primitive float to string
str =Double.toString(d); Primitive double to string
str = Long.toString(l); Primitive long to string

 

 

4. Converting string objects to numeric objects using the Static method ValueOf()

 

Method Calling  Conversion Action
DoubleVal = Double.Valueof(str); Converts string to Double object
FloatVal = Float.Valueof(str); Converts string to Float object
IntVal = Integer.Valueof(str); Converts string to Integer object
LongVal = Long.Valueof(str); Converts string to Long object

 

 

5. Converting numeric strings to primitive numbers using parsing methods

 

Method Calling Conversion Action
int i = Integer.parseInt(str); Converts string to primitive integer
long i = Long.parseLong(str); Converts string to primitive long

 

Note : parseInt() and parseLong() methods throw a NumberFormatException if the value of the str does not represent an integer.

 

 

EXAMPLE : -
public class WrapperExample{  
  public static void main(String args[]){  
     int a=20;  
     Integer i=Integer.valueOf(a);  
     Integer j=a;   
     System.out.println(a+" "+i+" "+j);  
  }
}  

About Author

Author Image
Lakshmi Singh

She is a backend Developer. She has expertise in Java, JavaScript, JQuery, HTML, CSS, PHP. She is a quick learner to new technologies and adaptive to the environment.

Request for Proposal

Name is required

Comment is required

Sending message..