What is the difference between Integer.parseInt and Integer.valueOf() ?

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){
;
}

2 comments:

  1. Hey there! Someone in my Myspace group shared this website with us so I came to check it out.I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers!Terrific blog and fantastic design and style.

    Bubble
    www.gofastek.com

    ReplyDelete
  2. The mind is a great philosopher. And life is not a philosophy, life is a reality. And philosophy is an escape from reality; philosophy means thinking. Life is, there is no question of thought. You can simply jump into it. You can simply experience it. Visit my site for more information.Thank you.

    n8fan.net

    www.n8fan.net

    ReplyDelete