Converting a string to an integer on Java / Android

How to convert String into Integer in Android or Java:

String strId="29";
int id = Integer.parseInt(strId);



String must be a number, other wise there should be an exception.

We can use try catch to handle exception or use following function for proper conversion.


int tryParseInt(String number) {  
     try {  
         return Integer.parseInt(number);  
      } catch (NumberFormatException e) {  
         return 0; // in cause of exception we should use any default value.


Call above function

String strId="29";
int id = tryParseInt(strId);


Leave a comment

Your email address will not be published. Required fields are marked *