Primitive
data types may be converted into object types by using the wrapper classes
contained in Java.
The
table below shows the simple data types and their corresponding wrapper class
types:
Simple
Type
|
Wrapper
Class
|
Boolean
|
Boolean
|
Char
|
Character
|
Double
|
Double
|
Float
|
Float
|
Int
|
Integer
|
Long
|
Long
|
Converting
Primitive numbers to object number using constructor 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.
|
Converting
object number to Primitive numbers using typeValue() methods:
Method
Calling
|
Conversion
Action
|
int i= intval.intValue();
|
Object to Primitive integer.
|
float f= floatval. floatValue();
|
Object to Primitive float.
|
double d=doubleval.doubleValue();
|
Object to Primitive double.
|
long l=longval.longValue();
|
Object to Primitive long.
|
Converting
number to String 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.
|
Converting
String object to numeric objects using the static methodValueOf():
Method
Calling
|
Conversion
Action
|
doubleval=Double.ValueOf(str);
|
Convert String to Double object.
|
floatval=Float.ValueOf(str);
|
Convert String to Float object.
|
intval=Integer.ValueOf(str);
|
Convert String to Integer object.
|
longval=Long.ValueOf(str);
|
Convert String to Long object.
|
Converting
Numeric String to primitive number using parsing method:
Method
Calling
|
Conversion
Action
|
int i=Integer.parseInt(str);
|
Convert String to primitive integer.
|
long l=Long.parseLong(str);
|
Convert String to primitive long.
|
No comments:
Write comments