By Unknown user


2011-04-07 18:27:54 8 Comments

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

30 comments

@ishant kulshreshtha 2019-02-06 20:13:51

Some of the ways to convert String into Int are as follows:

  1. You can use Integer.parseInt():

    String test = "4568";
    int new = Integer.parseInt(test);
    
  2. Also you can use Integer.valueOf():

    String test = "4568";
    int new = Integer.valueOf(test);
    

@Wai Ha Lee 2019-06-15 09:15:24

Both examples are the same

@Rob Hruska 2011-04-07 18:29:41

String myString = "1234";
int foo = Integer.parseInt(myString);

If you look at the Java Documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which of course you have to handle:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
   foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)

@Allison 2018-01-17 09:37:40

In addition to catching a NumberFormatException, the user should also be careful about the length of the strings they're passing in; if they're long enough to overflow an integer, they might want to consider using Long::parseLong instead.

@Letholdrus 2018-01-22 19:18:26

@Allison especially if using BIGINT field in a PostgreSQL auto incremented primary key field for instance. Much safer to use long

@JPRLCol 2018-01-25 20:17:14

You could check if the string is a Number first: stackoverflow.com/questions/1102891/…

@lokesh 2018-08-08 11:00:55

This method also throws exception when string is not a parsable integer in base 10. Use overloaded method to work in other bases. e.g. Integer.parseInt("1001", 8); for base 8. Source.

@Radioactive 2018-10-26 15:50:03

If you use Integer.parseInt prepare to put it inside a try catch block since this will throw are NumberFormat or InputMismatch Exception if it is not a valid number. Then in that case have proper exception handling at the catch block level. Otherwise as mentioned below you can also use the Integer class and then convert it to int.

@Alireza Fattahi 2016-07-26 05:26:27

As mentioned, Apache Commons' NumberUtils can do it. It returns 0 if it cannot convert a string to an int.

You can also define your own default value:

NumberUtils.toInt(String str, int defaultValue)

Example:

NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1)     = 1
NumberUtils.toInt(null, 5)   = 5
NumberUtils.toInt("Hi", 6)   = 6
NumberUtils.toInt(" 32 ", 1) = 1 // Space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty("  32 ", 1)) = 32;

@nxhoaf 2016-08-01 14:44:08

Apart from the previous answers, I would like to add several functions. These are results while you use them:

public static void main(String[] args) {
  System.out.println(parseIntOrDefault("123", 0)); // 123
  System.out.println(parseIntOrDefault("aaa", 0)); // 0
  System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
  System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
}

Implementation:

public static int parseIntOrDefault(String value, int defaultValue) {
  int result = defaultValue;
  try {
    result = Integer.parseInt(value);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex, endIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

@Vitalii Fedorenko 2016-08-06 17:56:29

Google Guava has tryParse(String), which returns null if the string couldn't be parsed, for example:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}

@Aditya 2016-08-18 07:07:24

For a normal string you can use:

int number = Integer.parseInt("1234");

For a String builder and String buffer you can use:

Integer.parseInt(myBuilderOrBuffer.toString());

@Raman Sahasi 2017-04-24 05:36:19

In programming competitions, where you're assured that number will always be a valid integer, then you can write your own method to parse input. This will skip all validation related code (since you don't need any of that) and will be a bit more efficient.

  1. For valid positive integer:

    private static int parseInt(String str) {
        int i, n = 0;
    
        for (i = 0; i < str.length(); i++) {
            n *= 10;
            n += str.charAt(i) - 48;
        }
        return n;
    }
    
  2. For both positive and negative integers:

    private static int parseInt(String str) {
        int i=0, n=0, sign=1;
        if (str.charAt(0) == '-') {
            i = 1;
            sign = -1;
        }
        for(; i<str.length(); i++) {
            n* = 10;
            n += str.charAt(i) - 48;
        }
        return sign*n;
    }
    
  3. If you are expecting a whitespace before or after these numbers, then make sure to do a str = str.trim() before processing further.

@Pankaj Mandale 2017-08-12 14:25:51

One method is parseInt(String). It returns a primitive int:

String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);

The second method is valueOf(String), and it returns a new Integer() object:

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);

@Peter Mortensen 2019-09-02 22:56:26

Isn't this covered in previous answers?

@Anup Gupta 2017-09-01 06:53:39

This is a complete program with all conditions positive and negative without using a library

import java.util.Scanner;


public class StringToInt {

    public static void main(String args[]) {
        String inputString;
        Scanner s = new Scanner(System.in);
        inputString = s.nextLine();

        if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
            System.out.println("Not a Number");
        }
        else {
            Double result2 = getNumber(inputString);
            System.out.println("result = " + result2);
        }
    }


    public static Double getNumber(String number) {
        Double result = 0.0;
        Double beforeDecimal = 0.0;
        Double afterDecimal = 0.0;
        Double afterDecimalCount = 0.0;
        int signBit = 1;
        boolean flag = false;

        int count = number.length();
        if (number.charAt(0) == '-') {
            signBit = -1;
            flag = true;
        }
        else if (number.charAt(0) == '+') {
            flag = true;
        }
        for (int i = 0; i < count; i++) {
            if (flag && i == 0) {
                continue;
            }
            if (afterDecimalCount == 0.0) {
                if (number.charAt(i) - '.' == 0) {
                    afterDecimalCount++;
                }
                else {
                    beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
                }
            }
            else {
                afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
                afterDecimalCount = afterDecimalCount * 10;
            }
        }
        if (afterDecimalCount != 0.0) {
            afterDecimal = afterDecimal / afterDecimalCount;
            result = beforeDecimal + afterDecimal;
        }
        else {
            result = beforeDecimal;
        }
        return result * signBit;
    }
}

@Dorian Gray 2017-11-10 11:38:23

There is no need to reinvent the wheel, just use Integer.parseInt.

@Anup Gupta 2017-11-11 05:38:46

@TobiasWeimer yes, we can do but this is without using library

@Dorian Gray 2017-11-11 08:15:04

I can see that, but what is the point not to use a library?

@Anup Gupta 2017-11-11 14:26:43

@TobiasWeimer, some people need this how to do without using Library.

@Dorian Gray 2017-11-11 15:00:06

No, no one needs it because it is a function inside the JDK, not some third party plugin.

@Lukas Bauer 2017-10-06 19:00:22

Use Integer.parseInt(yourString).

Remember the following things:

Integer.parseInt("1"); // ok

Integer.parseInt("-1"); // ok

Integer.parseInt("+1"); // ok

Integer.parseInt(" 1"); // Exception (blank space)

Integer.parseInt("2147483648"); // Exception (Integer is limited to a maximum value of 2,147,483,647)

Integer.parseInt("1.1"); // Exception (. or , or whatever is not allowed)

Integer.parseInt(""); // Exception (not 0 or something)

There is only one type of exception: NumberFormatException

@The Coding Wombat 2018-10-24 16:02:50

Does the int maximum value here also give a NumberFormatException?

@Lukas Bauer 2018-11-24 15:02:13

No, the maximum value is stil okay

@djm.im 2018-04-23 20:49:10

I am a little bit surprised that nobody mentioned the Integer constructor that takes String as a parameter.

So, here it is:

String myString = "1234";
int i1 = new Integer(myString);

Java 8 - Integer(String).

Of course, the constructor will return type Integer, and an unboxing operation converts the value to int.


It's important to mention: This constructor calls the parseInt method.

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}

@Poorna Senani Gamage 2018-07-27 08:45:03

public static int parseInt(String s)throws NumberFormatException

You can use Integer.parseInt() to convert a String to an int.

Convert a String, "20", to a primitive int:

String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);

Output-20

If the string does not contain a parsable integer, it will throw NumberFormatException:

String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

public static Integer valueOf(String s)throws NumberFormatException

You can use Integer.valueOf(). In this it will return an Integer object.

String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);

Output-20

References https://docs.oracle.com/en/

@Santosh Jadi 2018-09-12 09:07:04

It can be done in seven ways:

import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;

String number = "999";

1) Using Ints.tryParse:

int result = Ints.tryParse(number);

2) Using NumberUtils.createInteger:

Integer result = NumberUtils.createInteger(number);

3) Using NumberUtils.toInt:

int result = NumberUtils.toInt(number);

4) Using Integer.valueOf:

Integer result = Integer.valueOf(number);

5) Using Integer.parseInt:

int result = Integer.parseInt(number);

6) Using Integer.decode:

int result = Integer.decode(number);

7) Using Integer.parseUnsignedInt:

int result = Integer.parseUnsignedInt(number);

@Sundararaj Govindasamy 2019-02-05 16:24:14

NumberUtils handles null and empty scenarios as well.

@Nisarg 2018-11-09 15:24:12

Convert a string to an integer with the parseInt method of the Java Integer class. The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.

Overlooking the exception it can throw, use this:

int i = Integer.parseInt(myString);

If the String signified by the variable myString is a valid integer like “1234”, “200”, “1”, and it will be converted to a Java int. If it fails for any reason, the change can throw a NumberFormatException, so the code should be a little longer to account for this.

For example, Java String to int conversion method, control for a possible NumberFormatException

public class JavaStringToIntExample
{
  public static void main (String[] args)
  {
    // String s = "test";  // Use this if you want to test the exception below
    String s = "1234";

    try
    {
      // The String to int conversion happens here
      int i = Integer.parseInt(s.trim());

      // Print out the value after the conversion
      System.out.println("int i = " + i);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

If the change attempt fails – in this case, if you can try to convert the Java String test to an int — the Integer parseInt process will throw a NumberFormatException, which you must handle in a try/catch block.

@Peter Mortensen 2019-09-02 22:43:19

Why is s.trim() necessary?

@KIBOU Hassan 2017-04-28 16:59:44

Alternatively, you can use Integer.valueOf(). It will return an Integer object.

String numberStringFormat = "10";
Integer resultIntFormat = Integer.valueOf(numberStringFormat);
LOG.info("result:" + resultIntFormat);

Output: 10

@Rahul Sharma 2017-04-28 17:27:24

Duplicate answer.

@Peter Mortensen 2019-09-02 22:58:14

It is not the only duplicate answer. We are now at 93 answers (includes deleted) for this simple question.

@Phani Kumar 2018-11-29 13:44:40

Integer.parseInt(myString); - using the wrapper class

@Peter Mortensen 2019-09-02 22:37:59

This is already in the accepted answer (posted about 7 years prior).

@Sunil Dhappadhule 2019-01-14 08:03:26

You can use the Integer.parseInt() method.

Example:

String strNumber = "5790";
int extractNumber = Integer.parseInt(strNumber);

// The result will be --5790
System.out.println(extractNumber);

@Martin J.H. 2019-07-08 07:50:03

Duplicate answer

@Kevin Ng 2019-01-21 02:58:40

I wrote this fast method to parse a string input into int or long. It is faster than the current JDK 11 Integer.parseInt or Long.parseLong. Although, you only asked for int, I also included the long parser. The code parser below requires that the parser's method must be small for it to operate quickly. An alternative version is below the test code. The alternative version is pretty quick and it does not depend on the size of the class.

This class checks for overflow, and you could customize the code to adapt to your needs. An empty string will yield 0 with my method but that is intentional. You can change that to adapt your case or use as is.

This is only the part of the class where parseInt and parseLong are needed. Note that this only deals with base 10 numbers.

The test code for the int parser is below the code below.

/*
 * Copyright 2019 Khang Hoang Nguyen
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * @author: Khang Hoang Nguyen - [email protected]
 **/
final class faiNumber{
    private static final long[] longpow = {0L, 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L,
                                           10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L,
                                           1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L,
                                          };

    private static final int[] intpow = { 0, 1, 10, 100, 1000, 10000,
                                          100000, 1000000, 10000000, 100000000, 1000000000
                                        };

    /**
     * parseLong(String str) parse a String into Long.
     * All errors throw by this method is NumberFormatException.
     * Better errors can be made to tailor to each use case.
     **/
    public static long parseLong(final String str) {
        final int length = str.length();
        if (length == 0)
            return 0L;

        char c1 = str.charAt(0);
        int start;

        if (c1 == '-' || c1 == '+') {
            if (length == 1)
                throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));
            start = 1;
        } else {
            start = 0;
        }

        /*
         * Note: if length > 19, possible scenario is to run through the string
         * to check whether the string contains only valid digits.
         * If the check had only valid digits then a negative sign meant underflow, else, overflow.
         */
        if (length - start > 19)
            throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));

        long c;
        long out = 0L;

        for ( ; start < length; start++) {
            c = (str.charAt(start) ^ '0');
            if (c > 9L)
                throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            out += c * longpow[length - start];
        }

        if (c1 == '-') {
            out = ~out + 1L;
            // If out > 0 number underflow(supposed to be negative).
            if (out > 0L)
                throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));
            return out;
        }
        // If out < 0 number overflow (supposed to be positive).
        if (out < 0L)
            throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));
        return out;
    }

    /**
     * parseInt(String str) parse a string into an int.
     * return 0 if string is empty.
     **/
    public static int parseInt(final String str) {
        final int length = str.length();
        if (length == 0)
            return 0;

        char c1 = str.charAt(0);
        int start;

        if (c1 == '-' || c1 == '+') {
            if (length == 1)
                throw new NumberFormatException(String.format("Not a valid integer value. Input '%s'.", str));
            start = 1;
        } else {
            start = 0;
        }

        int out = 0; int c;
        int runlen = length - start;

        if (runlen > 9) {
            if (runlen > 10)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));

            c = (str.charAt(start) ^ '0'); // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
            if (c > 9)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            if (c > 2)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            out += c * intpow[length - start++];
        }

        for ( ; start < length; start++) {
            c = (str.charAt(start) ^ '0');
            if (c > 9)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            out += c * intpow[length - start];
        }

        if (c1 == '-') {
            out = ~out + 1;
            if (out > 0)
                throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
            return out;
        }

        if (out < 0)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        return out;
    }
}

Test Code Section. This should take around 200 seconds or so.

// Int Number Parser Test;
long start = System.currentTimeMillis();
System.out.println("INT PARSER TEST");
for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++){
   if (faiNumber.parseInt(""+i) != i)
       System.out.println("Wrong");
   if (i == 0)
       System.out.println("HalfWay Done");
}

if (faiNumber.parseInt("" + Integer.MAX_VALUE) != Integer.MAX_VALUE)
    System.out.println("Wrong");
long end = System.currentTimeMillis();
long result = (end - start);
System.out.println(result);
// INT PARSER END */

An alternative method which is also very fast. Note that array of int pow is not used, but a mathematical optimization of multiply by 10 by bit shifting.

public static int parseInt(final String str) {
    final int length = str.length();
    if (length == 0)
        return 0;

    char c1 = str.charAt(0);
    int start;

    if (c1 == '-' || c1 == '+') {
        if (length == 1)
            throw new NumberFormatException(String.format("Not a valid integer value. Input '%s'.", str));
        start = 1;
    } else {
        start = 0;
    }

    int out = 0;
    int c;
    while (start < length && str.charAt(start) == '0')
        start++; // <-- This to disregard leading 0. It can be
                 // removed if you know exactly your source
                 // does not have leading zeroes.
    int runlen = length - start;

    if (runlen > 9) {
        if (runlen > 10)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));

        c = (str.charAt(start++) ^ '0');  // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
        if (c > 9)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        if (c > 2)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        out = (out << 1) + (out << 3) + c; // <- Alternatively this can just be out = c or c above can just be out;
    }

    for ( ; start < length; start++) {
        c = (str.charAt(start) ^ '0');
        if (c > 9)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        out = (out << 1) + (out << 3) + c;
    }

    if (c1 == '-') {
        out = ~out + 1;
        if (out > 0)
            throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
        return out;
    }

    if (out < 0)
        throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
    return out;
}

@Kevin Ng 2019-09-07 06:11:31

Thank you, Peter, for making an edit for me. It looked pretty good. I was wondering if you can help me making a project based almost on this code that I started to become better. This is the link to the project github.com/kevinhng86/Java-host.fai.lib.faiNumber .

@Kevin Ng 2019-09-07 06:14:10

Also, to clarify. The reason why having the power array method ran faster is that Java cached the result for this type of test code. I tested, in a real-life situation, using bit shift will work way faster.

@Rajeev Ranjan 2019-02-11 13:15:50

You could use any of following:

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)

@mohamad sheikhi 2019-02-18 09:23:01

Use this method:

public int ConvertStringToInt(String number) {
    int num = 0;

    try {
        int newNumber = Integer.ParseInt(number);
        num = newNumber;
    } catch(Exception ex) {
        num = 0;
        Log.i("Console", ex.toString);
    }
    return num;
}

@nabeghe 2019-03-25 01:14:22

Custom algorithm:

public static int toInt(String value) {
  int output = 0;
  boolean isFirstCharacter = true;
  boolean isNegativeNumber = false;
  byte bytes[] = value.getBytes();
  for (int i = 0; i < bytes.length; i++) {
    char c = (char) bytes[i];
    if (!Character.isDigit(c)) {
      isNegativeNumber = (c == '-');
      if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
        throw new NumberFormatException("For input string \"" + value + "\"");
      }
    } else {
      int number = Character.getNumericValue(c);
      output = output * 10 + number;
    }
    isFirstCharacter = false;
  }
  if (isNegativeNumber)
    output *= -1;
  return output;
}

Another solution:

(Use the string charAt method instead of convert string to byte array)

public static int toInt(String value) {
  int output = 0;
  boolean isFirstCharacter = true;
  boolean isNegativeNumber = false;
  for (int i = 0; i < value.length(); i++) {
    char c = value.charAt(i);
    if (!Character.isDigit(c)) {
      isNegativeNumber = (c == '-');
      if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
        throw new NumberFormatException("For input string \"" + value + "\"");
      }
    } else {
      int number = Character.getNumericValue(c);
      output = output * 10 + number;
    }
    isFirstCharacter = false;
  }
  if (isNegativeNumber)
    output *= -1;
  return output;
}

Examples:

int number1 = toInt("20");
int number2 = toInt("-20");
int number3 = toInt("+20");
System.out.println("Numbers = " + number1 + ", " + number2 + ", " + number3);

try {
  toInt("20 Hadi");
} catch (NumberFormatException e) {
  System.out.println("Error: " + e.getMessage());
}

@Shiva Nandam Sirmarigari 2016-11-20 04:24:05

Here we go

String str="1234";
int number = Integer.parseInt(str);
print number;//1234

@Peter Mortensen 2019-09-02 23:01:56

This is already covered in the accepted answer (posted about 5 years prior).

@Abhijeet Kale 2018-12-25 10:33:05

import java.util.*;

public class strToint {

    public static void main(String[] args) {

        String str = "123";
        byte barr[] = str.getBytes();

        System.out.println(Arrays.toString(barr));
        int result = 0;

        for(int i = 0; i < barr.length; i++) {
            //System.out.print(barr[i]+" ");
            int ii = barr[i];
            char a = (char) ii;
            int no = Character.getNumericValue(a);
            result = result * 10 + no;
            System.out.println(result);
        }

        System.out.println("result:"+result);
    }
}

@Peter Mortensen 2019-09-02 22:35:04

Some explanation would be in order.

@Ram Chhabra 2018-09-07 09:59:44

Try this code with different inputs of String:

String a = "10";  
String a = "10ssda";  
String a = null; 
String a = "12102";

if(null != a) {
    try {
        int x = Integer.ParseInt(a.trim()); 
        Integer y = Integer.valueOf(a.trim());
        //  It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch
    } catch(NumberFormatException ex) {
        // ex.getMessage();
    }
}

@Alekya 2018-08-22 06:54:24

Use Integer.parseInt(), this will help you in parsing your string value to int.

Example:

String str = "2017";
int i = Integer.parseInt(str);
System.out.println(i);

output: 2017

@Dmytro Shvechikov 2017-10-03 19:16:06

Methods to do that:

 1. Integer.parseInt(s)
 2. Integer.parseInt(s, radix)
 3. Integer.parseInt(s, beginIndex, endIndex, radix)
 4. Integer.parseUnsignedInt(s)
 5. Integer.parseUnsignedInt(s, radix)
 6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
 7. Integer.valueOf(s)
 8. Integer.valueOf(s, radix)
 9. Integer.decode(s)
 10. NumberUtils.toInt(s)
 11. NumberUtils.toInt(s, defaultValue)

Integer.valueOf produces Integer object, all other methods - primitive int.

Last 2 methods from commons-lang3 and big article about converting here.

@Vishal Yadav 2017-09-14 19:45:41

Simply you can try this:

  • Use Integer.parseInt(your_string); to convert a String to int
  • Use Double.parseDouble(your_string); to convert a String to double

Example

String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55

@Dukeling 2017-12-30 19:43:26

This answer doesn't appear to add anything beyond the answers recommending Integer.parseInt posted a few years earlier (converting String to double would be a different question).

@David 2017-11-11 01:58:17

Use Integer.parseInt() and put it inside a try...catch block to handle any errors just in case a non-numeric character is entered, for example,

private void ConvertToInt(){
    String string = txtString.getText();
    try{
        int integerValue=Integer.parseInt(string);
        System.out.println(integerValue);
    }
    catch(Exception e){
       JOptionPane.showMessageDialog(
         "Error converting string to integer\n" + e.toString,
         "Error",
         JOptionPane.ERROR_MESSAGE);
    }
 }

@Oak 2014-03-20 23:51:19

Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code, but it could help others that are restricted like I was.

The first thing to do is to receive the input, in this case, a string of digits; I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";

Another limitation was the fact that I couldn't use repetitive cycles, therefore, a for cycle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

 // Obtaining the integer values of the char 1 and 2 in ASCII
 int semilastdigitASCII = number.charAt(number.length()-2);
 int lastdigitASCII = number.charAt(number.length()-1);

Having the codes, we just need to look up at the table, and make the necessary adjustments:

 double semilastdigit = semilastdigitASCII - 48;  //A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;

Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do.

We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit/10;

This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2

Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"

And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

  • No repetitive cycles
  • No "Magic" Expressions such as parseInt

@ChrisB 2015-08-14 14:23:54

Using type double for parsing an integer is not only a bad idea performance-wise. Values like 0.2 are periodic numbers in floating-point representation and cannot be represented precisely. Try System.out.println(0.1+0.2) to see the point -- the result will not be 0.3! Better stick with library code whereever you can, in this case Integer.parseInt().

@Holger 2016-03-04 10:47:41

It’s not clear what kind of problem this answer tries to solve, first, why anyone should ever have that restriction you describe, second, why you have to look at an ASCII table as you can simply use '0' for the character instead of 48 and never have to bother with its actual numeric value. Third, the entire detour with double values makes no sense at all as you are dividing by ten, just to multiply with ten afterwards. The result simply is semilastdigit * 10 + lastdigit as learnt in elementary school, when the decimal system was introduced…

@Oak 2016-05-02 08:49:52

@Holger I was personally given that restriction when first starting out programming, and also when I had to write (pen/paper) similar interactions in a test. It's uncommon, but it's a method that is easily understood and while not being the most efficient by miles it's a method that works decently enough for small projects. SO.SE is meant to help everyone, not just a few. I provided an alternative method, for those who are starting out by learning how to create a pseudo-algorithm and turning it into an algorithm rather than using premade java expressions. Although I did forget that '0' is cool

@Nathan Adams 2019-05-01 18:19:21

Why divide everything by 10 then multiply back by 10 again at the end?! Besides, "parseInt" isn't magic and it isn't an expression, it's an inbuilt library function that's been tested and proven over nearly 3 decades

@Thijser 2013-10-20 13:11:49

You can also begin by removing all non-numerical characters and then parsing the int:

string mystr = mystr.replaceAll( "[^\\d]", "" );
int number= Integer.parseInt(mystr);

But be warned that this only works for non-negative numbers.

@user289086 2014-10-11 14:00:14

This will cause -42 to be parsed as 42.

@Holger 2016-03-04 11:01:46

Yeah, this only works for non negative numbers which are correct to begin with and hence, don’t need this replacement step. For every other case, this attempt to automatically fix it, will make things worse (as almost every attempt to automatically fix something). If I pass in "4+2", I’ll get 42 as a result without any hint about that what I tried to do was misguided. The user will get the impression that entering basic expressions like 4+2 was a valid input, but the application continues with a wrong value. Besides that, the type is String, not string

@apm 2016-08-19 10:57:06

Or change first line to--> string mystr = mystr.replaceAll( "[^\\d\\-]", "" );

Related Questions

Sponsored Content

84 Answered Questions

65 Answered Questions

[SOLVED] What is the difference between String and string in C#?

39 Answered Questions

34 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3682529 View
  • 1544 Score
  • 34 Answer
  • Tags:   java string

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

3 Answered Questions

31 Answered Questions

[SOLVED] How do I check if a string is a number (float)?

23 Answered Questions

[SOLVED] How do I parse a string to a float or int?

27 Answered Questions

[SOLVED] Easiest way to convert int to string in C++

14 Answered Questions

[SOLVED] Convert JavaScript String to be all lower case?

  • 2008-09-30 20:22:35
  • Derek
  • 425156 View
  • 1252 Score
  • 14 Answer
  • Tags:   javascript string

Sponsored Content