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

 1. Integer.valueOf() returns an Integer object while Integer.parseInt() returns a primitive type.

// Program to show the use

// of Integer.parseInt() method

class Test1 {

public static void main(String args[])

{

String s = "77";

// Primitive int is returned

int str = Integer.parseInt(s);

System.out.print(str);

// Integer object is returned

int str1 = Integer.valueOf(s);

System.out.print(str1);

}

}

Output: 7777

2. Both String and Integer can be passed a parameter to Integer.valueOf() whereas only a String can be passed as parameter to Integer.parseInt().

// Program to show that Integer.parseInt()

// cannot take integer as parameter

class Test3 {

public static void main(String args[])

{

int val = 99;

try {

// It can take int as a parameter

int str1 = Integer.valueOf(val);

System.out.print(str1);

// It cannot take an int as a parameter

// Hence will throw an exception

int str = Integer.parseInt(val);

System.out.print(str);

}

catch (Exception e) {

System.out.print(e);

}

}

}

Error!
3. Integer.valueOf() can take a character as parameter and will return its corresponding unicode value whereas Integer.parseInt() will produce an error on passing a character as parameter.
// Program to test the method
// when a character is passed as a parameter

class Test3 {
public static void main(String args[])
{
char val = 'A';

try {

// It can take char as a parameter
int str1 = Integer.valueOf(val);
System.out.print(str1);

// It cannot take char as a parameter
// Hence will throw an exception
int str = Integer.parseInt(val);
System.out.print(str);
}
catch (Exception e) {
System.out.print(e);
}
}
}
Error!
Integer.parseInt()Integer.valueOf()
It can only take a String as a parameter.It can take a String as well as an integer as parameter.
It returns a primitive int value.It returns an Integer object.
When an integer is passed as parameter, it produces an error due to incompatible typesWhen an integer is passed as parameter, it returns an Integer object corresponding to the given parameter.
This method produces an error(incompatible types) when a character is passed as parameter.This method can take a character as parameter and will return the corresponding unicode.
This lags behind in terms of performance since parsing a string takes a lot of time when compared to generating one.This method is likely to yield significantly better space and time performance by caching frequently requested values.
If we need the primitive int datatype then Integer.parseInt() method is to be used.If Wrapper Integer object is needed then valueOf() method is to be used.

Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class