Learn how to convert String to Integer in Java using Integer.parseInt() and Integer.valueOf() methods. Includes examples, difference table, output, and exception handling.
Integer valueOf() Method :-
The Integer.valueOf(String s) method converts the specified String into an Integer object.
Syntax:- public static Integer valueOf(String s)
If we need a primitive int, then we can use:
int num = Integer.valueOf(str).intValue();
Integer.parseInt() Method :-
The Integer.parseInt(String s) method converts the specified String into a primitive int value. If we are only need a primitive integer value, parseInt() is generally preferred because it directly returns an int.
Syntax : public static int parseInt(String s)
public class InvalidNumberExample {
public static void main(String[] args) {
String str = "ABC";
// Integer.valueOf() Method
try {
int d = Integer.valueOf(str).intValue();
System.out.println("From valueOf method :- " + d);
} catch (NumberFormatException e) {
System.out.println("Invalid Number for valueOf()");
}
// Integer.parseInt() Method
try {
int num = Integer.parseInt(str);
System.out.println("From parseInt method :- " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid Number for parseInt()");
}
}
}
Output :-
From valueOf method :- 123
From parseInt method :- 123
Difference Between Integer.parseInt() and Integer.valueOf() in Java
Return Type :
Integer.parseInt() returns a primitive int value.
Integer.valueOf() returns an Integer object.
Object Creation :
parseInt() does not create an Integer object.
valueOf() returns an Integer object.
Use Case :
Use parseInt() when you only need a numeric value.
Use valueOf() when an Integer object is required, such as in collections.
Performance :
parseInt() is slightly faster because it returns a primitive int.
valueOf() may involve object creation or caching.