How to convert String to int in java manually/ without using java library


In this tutorial we will convert String to int in Java manually i.e. without using any java library with exception handling. If number is not valid then NumberFormatException is thrown.




Program/Example to convert String to int in Java manually/i.e. without using java library with exception handling.
In this example we will convert String to int in Java manually. We will also check whether number is numeric or not.
package StringToInt;
public class ConvertStringToIntWithoutUsingJavaLibraryExample {
   public static void main(String[] args) {
          String string = "123";
          int n = convertStringToInteger(string);
          System.out.println(n);
   }
  
   public static int convertStringToInteger( String string ){
   int i = 0;
   int n = 0;
   boolean numberIsNegative = false;
   //check number is negative or not
   if (string.charAt(0) == '-') {
     numberIsNegative = true;
       i++;
   }
   while( i < string.length()) {
       n *= 10;
      
       //Check character is numeric
       //LOGIC = ASCII value of 0 is 48, ASCII value of 9 is 57
       if( string.charAt(i)< 48 || string.charAt(i) >57 ){
         throw new NumberFormatException("String is not numeric");
       }
      
     //ASCII value of 1 is 49, 2 is 50 and so on.
       //Example 1 = for char value 1, ASCII value is 49,
       //              So storing char value 1 (i.e. ASCII value 49) in int will result in 49.
       //              subtracting 48 from char value 1 (i.e. ASCII value 49) will store 1 in int.
       //Example 2 = for char value 2, ASCII value is 50,
       //              So storing char value 2 (i.e. ASCII value 50) in int will result in 50.
       //              subtracting 48 from char value 2 (i.e. ASCII value 50) will store 2 in int.
       n += string.charAt(i) - 48;
       i++;
   }
   if (numberIsNegative)
       n = -n;
  
   return n;
   }
}
/*OUTPUT

123
*/

Summary -
So in this tutorial we converted String to int in Java manually i.e. without using any java library with exception handling. If number is not valid then NumberFormatException is thrown.

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy(JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

How to convert ArrayList to HashSet and Set to Array in Java examples

Collection - List, Set and Map all properties in tabular form


eEdit
Must read for you :