Use the lines of code mentioned below:-
String myString = "1234";
int foo = Integer.parseInt(myString);
The documentation of Java mentions that the "catch" is when this function can throw a NumberFormatException, which you can handle by using the code mentioned below:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}
This will ensure that they default a malformed number to 0, but you could try another way if wished upon. However, you can also use an Ints method from the Guava library, which is in combination with Java 8's Optional and hence, this makes a more powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)