foote

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


 String myString = "1234";

int foo = Integer.parseInt(myString);

int foo; try { foo = Integer.parseInt(myString); } catch (NumberFormatException e) { foo = 0; }

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a 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)
How do I convert a String to an int in Java? How do I convert a String to an int in Java? Reviewed by Udochi V.C on January 02, 2022 Rating: 5

No comments:

Powered by Blogger.