String to Integer using Integer.parseInt() String to Integer using Integer.valueOf()

Let’s say you have a string – strTest – that contains a numeric value. Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error. Output: Hence, you need to convert a String to int before you peform numeric operations on it

Example 1: Convert String to Integer using Integer.parseInt()

Syntax of parseInt method as follows: Pass the string variable as the argument. This will convert the Java String to java Integer and store it into the specified integer variable. Check the below code snippet- Output:

Example 2: Convert String to Integer using Integer.valueOf()

Integer.valueOf() Method is also used to convert String to Integer in Java. Following is the code example shows the process of using Integer.valueOf() method: Output:

NumberFormatException

NumberFormatException is thrown If you try to parse an invalid number string. For example, String ‘Guru99’ cannot be converted into Integer. Example: Above example gives following exception in output: