Java Convert String to int

How can I convert a String to an int in Java?

To convert a string into an integer in java you can use Integer.parseInt() function.

Example of Integer.parseInt() function

This is an example which converts string "123" into a primitive integer 123.
String numString = "123";
int number = Integer.parseInt(numString);
System.out.println(number);

/* Output of above code:-

123

*/

Example of Integer.valueOf() function

Alternatively, Integer.valueOf() function can be used to convert string to int in java. This function returns an Integer object.
String numString = "123";
int number = Integer.valueOf(numString);
System.out.println(number);

/* Output of above code:-

123

*/

NumberFormatException

If in case, the string does not contain a parsable integer the NumberFormatException occurs.

Example of NumberFormatException

String numString = "123A";
int number = Integer.parseInt(numString);
System.out.println(number);

/* Output of above code:-

Exception in thread "main" java.lang.NumberFormatException: For input string: "123A"
 at java.lang.NumberFormatException.forInputString(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at java.lang.Integer.valueOf(Unknown Source)

*/
By looking at the Java Documentation you'll notice the "catch" is that this function can throw a NumberFormatException. You need to handle this exception.

Handling NumberFormatException

If the number in the string is malformed then code given below will make it 0. You can also handle this in some other way.
int number;
try
{
	number = Integer.parseInt(numString);
}
catch (NumberFormatException e)
{
	numgber = 0;
}
If you do not want to handle the exception you can use Ints method from the Guava library to convert string to an integer in java.

Example

import com.google.common.primitives.Ints;

String numString = "123";
int number= Optional.ofNullable(numString)
 .map(Ints::tryParse)
 .orElse(0)

System.out.println(number);

/* Output of above code:-

123

*/