String myString = "1234";
int foo = Integer.parseInt(myString);
On the off chance that you take a gander at the Java documentation, you'll see the "get" is that this capacity can toss a
NumberFormatException
, which obviously you need to deal with
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
foo = 0;
}
(This treatment defaults a deformed number to
0
, however you can accomplish something different on the off chance that you like.)
On the other hand, you can utilize an
Ints
technique from the Guava library, which in mix with Java 8's Optional, makes for an amazing and brief approach to change over a string into an int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)