While working on an application there are several instances when you want to convert a string to int in Java 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.
Integer class in Java 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.
Converting String to int in Java- Using Integer.parseInt()
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
Converting String to int in Java- Using Integer.valueOf()
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 while converting String to int
If conversion from String to integer fails then NumberFormatExcpetion is thrown. So, it is better to enclose your conversion code with in a try-catch block.
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 Convert String to int in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment