How to convert a String to int in Java

The only requirement to convert a string to an integer in java is that it must contain only digits that you want to put in a variable of type int, except for the first character that indicates a negative "-" or positive "+" value. For example, the result of "-123" is the number -123.
Many will cast, but java doesn't allow it.

cannot Cast from string to int

The exception Cannot cast from String to int means that the Java compiler does not allow a String to cast to int. This makes sense since the two are not of the same type.

The Integer

The Integer object contains a single attribute of type int. This class contains several methods to convert an int to a String and a String to an int.

1) By instantiating a new Integer(String s)

This constructor allocates a new object containing an integer:

public class Cast {

public static void main(String[] args) {
String nbs = "12";
int nb;
nb = new Integer(nbs);
System.out.println(nb);
}
}
Output:

12

2) With the Integer.valueOf(String s)

The valueOf() returns a new instance of java.lang.Integer which contains the value represented in the argument String.

public class Cast {

public static void main(String[] args) {
String nbs = "12";
int nb;
nb = new Integer(nbs);
System.out.println(nb);
}
}
Output:

12

3) With the Integer.parseInt(String s)

The parseInt() returns an integer value, just as if the argument was passed in the valueOf(String s).

public class Cast {

public static void main(String[] args) {
String nbs = "12";
int nb;
nb = Integer.parseInt(nbs);
System.out.println(nb);
}
}
Output:

12

Exception NumberFormatException thrown

NumberFormatException is called if the argument passed is not in the correct format. The causes are:
  • The passed argument contains at least one non-numeric character.
  • The number is not decimal like the float 12.4f.

Improving our procedure

To avoid the program terminating, we will return a default value if the format is not respected.

public class Cast {

public static void main(String[] args) {
String nbs = "12.4s";
int nb;
System.out.println(stringToInt(nbs,0));
}

public static int stringToInt(String value, int _default) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return _default;
}
}
}
Output:

0
In the case where the variable nbs is not numeric, the function stringToInt() returns 0 by default.

References:
Oracle.com -  The Integer
JRJC-Convert string to int