Converting String to int in Java?
2Answer
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
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