When we write Integer.parseInt("11"); then the return type is primitive type.
But when we write Integer.valueOf("11") returns the Integer wrapper type(Object).
For all the primitives and wrappers same is applicable.
So
For int:
int i = Integer.parseInt(str);
is same as
Integer I = Integer.valueOf(str);
int i1 = I.intValue();
Here is another example for the string presents a hexdecimal string:
int i = Integer.parseInt(str, 16 );
# Convert String to short:
try {
short s = Short.parseShort(str);
/* or */
Short S = Short.valueOf(str);
short s1 = S.shortValue();
}
catch (NumberFormatException e){
;
}
# Convert String to byte:
try {
byte b = Byte.parseByte(str);
/* or */
Byte B = Byte.valueOf(str);
byte b1 = B.byteValue();
}
catch (NumberFormatException e){
;
}
# Convert String to long:
try {
long l = Long.parseLong(str);
/* or */
Long L = Long.valueOf(str);
long l1 = L.longValue();
}
catch (NumberFormatException e){
;
}
# Convert String to float:
try {
float f = Float.parseFloat(str);
float f1 = Float.valueOf(str).floatValue();
}
catch (NumberFormatException e){
;
}
# Convert String to double:
try {
double d= Double.parseDouble(str);
double d1 = Double.valueOf(str).doubleValue();
}
catch (NumberFormatException e){
;
}
# Convert String to boolean:
Boolean B = Boolean.valueOf(str);
boolean b= B.booleanValue();
# Convert String to char:
try {
char c= str.charAt(0);
}
catch (IndexOutOfBoundsException e){
;
}
No comments:
Post a Comment