And what is wrong with this?

int i = Integer.parseInt(str);

EDIT :

If you really need to do the conversion by hand, try this:

public static int myStringToInteger(String str) {
    int answer = 0, factor = 1;
    for (int i = str.length()-1; i >= 0; i--) {
        answer += (str.charAt(i) - '0') * factor;
        factor *= 10;
    }
    return answer;
}

The above will work fine for positive integers - assuming that the string only contains numbers, otherwise the result is undefined. If the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.

Answer from Óscar López on Stack Overflow
Top answer
1 of 3
12

To improve your intToString() method you should consider using a StringBuilder, and specifically the method StringBuilder.append(int).

Iterate digits in your int, and for each digit you can append(eachDigit) to the StringBuilder element. This will also reduce the complexity of intToString() to \ since you do not need to create a new String instance each iteration. To get a String object from the StringBuilder, use StringBuilder.toString(). Or, if you are not allowed, you can use StringBuilder.subString(0).

You should also use a StringBuilder.append() (using the same idea) to reverse the resulting string (your second loop in your code).

Since it is not homework (as per comments), I have no problems providing a code snap. It should look something like this:

public static String intToString(int n) { 
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();
    while (n > 0) { 
        int curr = n % 10;
        n = n/10;
        sb.append(curr);
    }
    String s = sb.substring(0);
    sb = new StringBuilder();
    for (int i = s.length() -1; i >= 0; i--) { 
        sb.append(s.charAt(i));
    }
    return sb.substring(0);
}

Notes:

  • You can also use StringBuilder.reverse() instead of the second loop.
  • In here, \ means linear in the the number of digits in the input number (n is the number of digits in the input number - not the number itself!) If you are looking for the complexity in terms of the initial number (it is \) since you divide your element by 10 each iterations, you have a total of \ iterations for each loop, which results in \.
2 of 3
2

For your example , I should point out some problems : first , when you add two add string frequently, you should use StringBuilder instead ; second , you should consider Integer.MIN_VALUE into account!Here is my code:

public static String parseInt(int integer)
{
    boolean ifNegative = integer<0;
    boolean ifMin = integer == Integer.MIN_VALUE;
    StringBuilder builder = new StringBuilder();        
    integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer;    
    List<Integer> list = new LinkedList<Integer>(); 
    int remaining = integer;
    int currentDigit = 0 ;

    while(true)
    {
        currentDigit = remaining%10;
        list.add(currentDigit);
        remaining /= 10;
        if(remaining==0) break;
    }

    currentDigit = list.remove(0);
    builder.append(ifMin?currentDigit+1:currentDigit);
    for(int c : list)
        builder.append(c);
    builder.reverse().insert(0, ifNegative?'-':'+');
    return builder.toString();
}
🌐
Blogger
javahungry.blogspot.com › 2014 › 02 › how-to-convert-string-to-int-in-java-without-using-integer-parseint-method-code-with-example.html
How to convert string to int in java without using integer parseInt() method : Code with example | Java Hungry
Converting String to Integer : Pseudo Code 1. Start number at 0 2. If the first character is '-' Set the negative flag Start scanning with the next character For each character in the string Multiply number by 10 Add( digit number - '0' ) to number If negative flag set Negate number Return number Java Code :
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-string-to-int-in-java
String to int in Java - GeeksforGeeks
The Integer.valueOf() method converts a String to an Integer object instead of a primitive int. We can unbox it to an int. Note: valueOf() method uses parseInt() internally to convert to integer. Java ·
Published   July 23, 2025
🌐
Quora
quora.com › Can-a-string-be-converted-to-an-integer-without-using-parseInt-or-Integer-parseInt-methods-in-Java
Can a string be converted to an integer without using parseInt() or Integer.parseInt() methods in Java? - Quora
Answer (1 of 2): Yes , You can do with valueOf() method. Example 1: String str=”100″; Integer num=new Integer (8); num=Integer.valueOf(str); Example 2: Below program illustrates the java.lang.Integer.valueOf(String str, int base) method: ...
🌐
Baeldung
baeldung.com › home › java › java string › convert string to int or integer in java
Convert String to int or Integer in Java | Baeldung
December 15, 2023 - Therefore, it’s highly recommended to use valueOf() instead of parseInt() to extract boxed integers as it may lead to a better overall footprint for our application. ... @Test public void givenString_whenCallingIntegerConstructor_shouldCo...
Top answer
1 of 2
1

Converting String to int without any library function

public static int stringToInt(String number) {
    int res = 0;
    for (int i = 0; i < number.length(); i++) {
        res = res * 10 + number.charAt(i) - '0';
    }
    return res;
}

Perform whatever calculation you want to perform and then use the following method to convert the int back to String without any library function

Converting int to String without any library function

   public static String parseInt(int integer)
{
    boolean ifNegative = integer<0;
    boolean ifMin = integer == Integer.MIN_VALUE;
    StringBuilder builder = new StringBuilder();        
    integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer;    
    List<Integer> list = new LinkedList<Integer>(); 
    int remaining = integer;
    int currentDigit = 0 ;

    while(true)
    {
        currentDigit = remaining%10;
        list.add(currentDigit);
        remaining /= 10;
        if(remaining==0) break;
    }

    currentDigit = list.remove(0);
    builder.append(ifMin?currentDigit+1:currentDigit);
    for(int c : list)
        builder.append(c);
    builder.reverse().insert(0, ifNegative?'-':'+');
    return builder.toString();
}
2 of 2
1

The source code for Integer.parseInt is available on GrepCode. It uses a package-private method to generate NumberFormatException errors, but you can leave those out and the code will still work for valid strings.

public static int parseInt(String s, int radix) {
    int result = 0;
    boolean negative = false;
    int i = 0, len = s.length();
    int limit = -Integer.MAX_VALUE;
    int multmin;
    int digit;

    if (len > 0) {
        char firstChar = s.charAt(0);
        if (firstChar < '0') {
            if (firstChar == '-') {
                negative = true;
                limit = Integer.MIN_VALUE;
            }
            i++;
        }
        multmin = limit / radix;
        while (i < len) {
            digit = Character.digit(s.charAt(i++), radix);
            result *= radix;
            result -= digit;
        }
    }
    return negative ? result : -result;
}
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › java › how do i convert a string to an int in java?
How do I convert a String to an int in Java? | Sentry
class Main { public static void main(String[] args) { String validString = "123"; String invalidString = "123x"; int number; try { number = Integer.parseInt(validString); System.out.println("Converted integer: " + number); number = Integer.parseInt(invalidString); System.out.println("Converted integer: " + number); } catch (NumberFormatException e) { System.out.println("Invalid integer input"); } } } Modern Java versions running on modern systems are very efficient and there should be practically no performance difference between using primitive int and declaring new Integer objects, so you should consider convenience over performance in nearly all cases.
🌐
Coderanch
coderanch.com › t › 379494 › java › Converting-String-Integer-losing-leading
Converting String to Integer without losing leading zero's (Java in General forum at Coderanch)
If you really need to convert this bitstring to an integer then you need to do Integer.parseInt(string, 2) ; What you probably should do, if you really need to pass an integer, rather than the bitstring in string form is to pass the number as shown above and then, inside the routine that is ...
🌐
freeCodeCamp
freecodecamp.org › news › java-string-to-int-how-to-convert-a-string-to-an-integer
Java String to Int – How to Convert a String to an Integer
November 23, 2020 - If we want to make a simple calculator ... – how can we convert a string to an integer? In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer....
🌐
Coderanch
coderanch.com › t › 649714 › java › converting-decimal-integer-parseInt-method
converting to decimal but without using integer.parseInt() method (Beginning Java forum at Coderanch)
So i did a search and saw that everyone was using the integer.parseInt(String , int radix) method to convert a binary string to int which worked completely fine, however, the only problem is we didn't take this with my professor so I'm not sure if it's OK and that maybe he wants another way to convert ?
🌐
SitePoint
sitepoint.com › general web dev
String to integer conversion in Java - General Web Dev - SitePoint Forums | Web Development & Design Community
July 8, 2022 - For one of my project I have to convert String to integer. How to convert “16:45:20” string to integer in java. I am using int time = Integer.parseInt(string) It’s giving me a NumberFormatException error. How to solve…
🌐
Reddit
reddit.com › r/java › convert string to int?
r/java on Reddit: Convert string to int?
September 11, 2014 -

I'm creating a program of a "yes or no" quiz. At the end, the program is supposed to add up the number of yes and nos and give a result that corresponds to the total.

Example: If someone answered yes for all six questions, that would equal '6'. If someone answer yes four times and no twice, that would equal '4'.

I have the program looking pretty good. But I do have one problem that I can't figure out.

When a questioned is asked, the user types in 'yes' or 'no'. I need the yes to convert to 1 and the no to convert to 0 for the program to work.

I need a way to convert the user entry 'yes' or 'no' to '1' and '0', respectively.

Anyone know how to get this to work or point me in the right direction?

🌐
Devmio
devm.io › java › convert-java-string-int-134101
How to convert a Java String to an Int
In this tutorial, Allice Watson, explains how a String can be converted into an int data type in Java [examples included].
🌐
Java67
java67.com › 2015 › 08 › 2-ways-to-parse-string-to-int-in-java.html
2 ways to parse String to int in Java - Example Tutorial | Java67
So every time you pass a numeric String which is in the range of -128 to 127, Integer.valueOf() doesn't create a new Integer object but returns the same value from the cached pool. The only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like the parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to an int value in Java.
🌐
GeeksforGeeks
geeksforgeeks.org › java › different-ways-for-integer-to-string-conversions-in-java
Java Convert int to String | How to Convert an Integer into a String - GeeksforGeeks
April 9, 2025 - Note: This method is not efficient as an instance of the Integer class is created before conversion is performed. And deprecated and marked as removal. Here, we will declare an empty string and using the '+' operator, we will simply store the resultant as a string. Now by this, we are successfully able to append and concatenate these strings. ... // Java Program to Illustrate Integer to String Conversions // Using Concatenation with Empty String class Geeks { // Main driver method public static void main(String args[]) { // Custom integer values int a = 1234; int b = -1234; // Concatenating with empty strings String str1 = "" + a; String str2 = "" + b; // Printing the concatenated strings System.out.println("String str1 = " + str1); System.out.println("String str2 = " + str2); } }