To convert String to int in Java you can use one of the following options-
- Integer.parseInt(String str) method which returns the passed String as int.
- Integer.valueOf(String str) method which returns the passed String as Integer.
Java example to convert String to int using Integer.parseInt()
public class StringToInt { public static void main(String[] args) { String str = "12"; try{ int num = Integer.parseInt(str); System.out.println("value - " + num); // can be used in arithmetic operations now System.out.println(num+"/3 = " + num/3); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); } } }
Output
value - 12 12/3 = 4
Java example to convert String to int using Integer.valueOf
public class StringToInt { public static void main(String[] args) { String str = "12"; try{ Integer num = Integer.valueOf(str); System.out.println("value - " + num); // can be used in arithmetic operations now System.out.println(num+"/3 = " + num/3); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); } } }
Output
value - 12 12/3 = 4
In this example you can see that valueOf() method returns Integer object, because of autoboxing it can directly be used as int value though.
NumberFormatException
In the examples you can see a try-catch block which catches NumberFormatException which is thrown if an invalid number string is passed for converting to int.
public class StringToInt { public static void main(String[] args) { String str = "123ab"; try{ Integer num = Integer.valueOf(str); System.out.println("value - " + num); // can be used in arithmetic operations now System.out.println(num+"/3 = " + num/3); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); throw exp; } } }
Output
Error in conversion For input string: "123ab" Exception in thread "main" java.lang.NumberFormatException: For input string: "123ab" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.valueOf(Unknown Source) at com.knpcode.programs.StringToInt.main(StringToInt.java:8)
Related Posts
- How to Convert String to float in Java
- How to Convert String to double in Java
- Java Program to Convert Numbers to Words
- How to Convert float to int in Java
- How to Convert double to int in Java
- Java Program to Check if Armstrong Number
- Display Time in 24 Hour Format in Java
- Merge Sort Java Program
That’s all for the topic How to Convert String to int in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like