While working on an application there are several instances when you want to convert a string to int because -
- Your web application page takes every thing as string and later you convert values to int (if required)
- There is a method that takes int as parameter and the value you have is String which you need to convert to int before passing it as parameter to the method.
In Java Integer class provides two methods for converting string to int.
- parseInt(String s)– This method returns the integer value represented by the string argument. NumberFormatException is thrown if the string does not contain a parsable integer.
- valueOf(String s)– This method returns an Integer object holding the value of the specified String. NumberFormatException is thrown if the string cannot be parsed as an integer.
Here Few things to note are -
- Both of the methods are static so you can use them directly with the class i.e. Integer.parseInt(String s) and Integer.valueOf(String s).
- If you have noticed parseInt() method returns int (primitive data type) where as valueOf() method returns Integer object.
- String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
Integer.parseInt() example
public class StringToint {
public static void main(String[] args) {
String num = "7";
try{
int value = Integer.parseInt(num);
System.out.println("value " + value);
}catch(NumberFormatException neExp){
System.out.println("Error while conversion " +
neExp.getMessage());
}
}
}
Output
value 7
Integer.valueOf() example
public class StringToInteger {
public static void main(String[] args) {
String num = "7";
try{
Integer value = Integer.valueOf(num);
System.out.println("value " + value.intValue());
}catch(NumberFormatException neExp){
System.out.println("Error while conversion " +
neExp.getMessage());
}
}
}
Output
value 7
NumberFormatExcpetion
If conversion fails then NumberFormatExcpetion is thrown. So, it is better to enclose your conversion code with in a try-catch block.
Example code
public class StringToint {
public static void main(String[] args) {
String num = "7abc";
try{
int value = Integer.parseInt(num);
System.out.println("value " + value);
}catch(NumberFormatException neExp){
System.out.println("Error while conversion " +
neExp.getMessage());
}
}
}
Output
Error while conversion For input string: "7abc"
That's all for this topic Converting string to int - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -