Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

like image 796
Unknown user Avatar asked Apr 07 '11 18:04

Unknown user


Video Answer


2 Answers

String myString = "1234"; int foo = Integer.parseInt(myString); 

If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which you can handle:

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) 
like image 60
Rob Hruska Avatar answered Oct 03 '22 11:10

Rob Hruska


For example, here are two ways:

Integer x = Integer.valueOf(str); // or int y = Integer.parseInt(str); 

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

like image 44
lukastymo Avatar answered Oct 03 '22 09:10

lukastymo