• support@answerspoint.com

Converting String to int in Java?

2246

How can a String be converted 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.

2Answer


0
int foo = Integer.parseInt("1234");

See the Java Documentation for more information.

(If you have it in a StringBuffer, you'll need to do Integer.parseInt(myBuffer.toString());instead).

  • answered 8 years ago
  • Gul Hafiz

0

Well a very important point to consider is that Integer parser throws NumberFormatException as stated in Javadoc.

int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
      //Will Throw exception!
      //do something! anything to handle the exception.
}

try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
      //No problem this time but still it is good practice to care about exceptions.
      //Never trust user input :)
      //do something! anything to handle the exception.
}

It is important to handle this exception when trying to get integer values from splitted arguments or dynamically parsing something.

  • answered 8 years ago
  • Sunny Solu

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2246 times
  • active 9 years ago

Best Rated Questions