javacodex.com
Java Examples
Java Examples
memu home questions

How to convert a String to an Int without using the Integer.ParseInt() method?

Here is an example on how to convert a String to an Int in java without using the Integer.ParseInt() method

StringtoInt.java

public class StringtoInt {
 
   public static void main (String args[]) {
      String str = "2468";
      System.out.println("String value: " + str);
 
      int num = stringToint(str);
      System.out.println("int value: "+ num);
   }
 
   public static int stringToint( String str ) {
      int i = 0; 
      int number = 0;
      boolean isNegative = false;
      int len = str.length();
      if( str.charAt(0) == '-' ){
         isNegative = true;
         i = 1;
      }
      while( i < len ){
         number *= 10;
         number += ( str.charAt(i++) - '0' );
      }
      if( isNegative ) {
        number = -number;
      }
      return number;
   }   
}
 

output

$ java StringtoInt
String value: 2468
int value: 2468

Questions answered by this page:

Write a program to convert string to number without using Integer.parseInt() method. Manually converting a string to an integer in Java Convert string to integer without using parseInt method




Contact: javacodex@yahoo.com