Как мне преобразовать строку в int в Java?

Как я могу конвертировать String для int на яве?

Моя строка содержит только цифры, и я хочу вернуть число, которое она представляет.

Например, учитывая строку "1234" результат должен быть числом 1234,

59 ответов

Вы можете использовать любое из следующих:

  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)

Кстати, имейте в виду, что если строка имеет значение null, вызов:

int i = Integer.parseInt(null);

генерирует NumberFormatException, а не NullPointerException.

Два основных способа сделать это - использовать метод valueOf() и метод parseInt() из Integer учебный класс.

Предположим, вам дана такая строка

String numberInString = "999";

Затем вы можете преобразовать его в целое число, используя

int numberInInteger = Integer.parseInt(numberInString);

Или вы можете использовать

int numberInInteger = Integer.valueOf(numberInString);

Но дело в том, что метод Integer.valueOf() имеет следующую реализацию в Integer учебный класс:

public static Integer valueOf(String var0, int var1) throws NumberFormatException {
    return parseInt(var0, var1);
}

Как видите, Integer.valueOf() внутренние звонки Integer.parseInt()сам. Также,parseInt() возвращает int, а также valueOf() возвращает Integer

public static int parseInt(String s) выбрасывает NumberFormatException

Вы можете использовать пользователя Integer.parseInt() преобразовать строку в int.

преобразовать строку 20 в примитив int.

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

Выход-20

если строка не содержит анализируемого целого числа. это будет брошено NumberFormatException

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

public static Integer valueOf(String s) выдает NumberFormatException

ты можешь использовать Integer.valueOf(), в этом он вернет объект Integer.

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

Выход-20

Ссылки https://docs.oracle.com/en/

Импорт java.util.*;

открытый класс 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);
    }

}

Преобразовать строку в целое число с помощью parseInt метод класса Java Integer. parseInt Метод состоит в том, чтобы преобразовать String в int и бросает NumberFormatException если строка не может быть преобразована в тип int.

Пропустив исключение, которое он может выдать, используйте это:

int i = Integer.parseInt(myString);

Если строка, обозначенная переменной myString допустимое целое число, подобное “1234”, “200”, “1”, и он будет преобразован в Java int. Если по какой-либо причине это не удается, изменение может привести к NumberFormatException, поэтому код должен быть немного длиннее, чтобы учесть это.

Ex. Джава String в int метод конвертации, контроль за возможным 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());
    }
  }
}

Если попытка изменения не удалась - в случае, если вы можете попытаться преобразовать тест Java String в int - Integer parseInt процесс бросит NumberFormatException, который вы должны обработать в блоке try/catch.

Integer.parseInt(myString); - используя класс-оболочку

Для Android-разработчиков, оказавшихся здесь, это различные решения для Kotlin :

      // Throws exception if number has bad form
val result1 = "1234".toInt()
      // Will be null if number has bad form
val result2 = "1234"
    .runCatching(String::toInt)
    .getOrNull()
      // Will be the given default if number has bad form
val result3 = "1234"
    .runCatching(String::toInt)
    .getOrDefault(0)
      // Will be return of the else block if number has bad form
val result4 = "1234"
    .runCatching(String::toInt)
    .getOrElse {
        // some code
        // return an Int
    }

Используя этот метод, вы можете избежать ошибок.

String myString = "1234";
int myInt;
if(Integer.parseInt(myString), out myInt){};

У вас могут быть свои собственные реализации для этого, например:

public class NumericStringToInt {

    public static void main(String[] args) {
        String str = "123459";

        int num = stringToNumber(str);
        System.out.println("Number of " + str + " is: " + num);
    }

    private static int stringToNumber(String str) {

        int num = 0;
        int i = 0;
        while (i < str.length()) {
            char ch = str.charAt(i);
            if (ch < 48 || ch > 57)
                throw new NumberFormatException("" + ch);
            num = num * 10 + Character.getNumericValue(ch);
            i++;
        }
        return num;
    }
}

Как я пишу на GitHub:

public class StringToInteger {
    public static void main(String[] args) {
        assert parseInt("123") == Integer.parseInt("123");
        assert parseInt("-123") == Integer.parseInt("-123");
        assert parseInt("0123") == Integer.parseInt("0123");
        assert parseInt("+123") == Integer.parseInt("+123");
    }

    /**
     * Parse a string to integer
     *
     * @param s the string
     * @return the integer value represented by the argument in decimal.
     * @throws NumberFormatException if the {@code string} does not contain a parsable integer.
     */
    public static int parseInt(String s) {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        boolean isNegative = s.charAt(0) == '-';
        boolean isPositive = s.charAt(0) == '+';
        int number = 0;
        for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
            if (!Character.isDigit(s.charAt(i))) {
                throw new NumberFormatException("s=" + s);
            }
            number = number * 10 + s.charAt(i) - '0';
        }
        return isNegative ? -number : number;
    }
}

Это может сработать,

Integer.parseInt(yourString);

Существуют различные способы преобразования строкового значения int в значение типа данных Integer. Вам необходимо обработать NumberFormatException для проблемы со строковым значением.

  1. Integer.parseInt

     foo = Integer.parseInt(myString);
    
  2. Integer.valueOf

     foo = Integer.valueOf(myString);
    
  3. Использование дополнительного API Java 8

     foo = Optional.of(myString).map(Integer::parseInt).get();
    

Попробуйте этот код с разными входами строки

        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();
        }
        }

Преобразование String в int или Integer - очень распространенная операция в Java. Есть несколько простых способов выполнить это базовое преобразование.

Integer.parseInt()

Одним из основных решений является использование специального статического метода Integer: parseInt (), который возвращает примитивное значение типа int.

      public class StringToInt {
public static void main(String args[]) {
    String s = "200";
    try {
        int i = Integer.parseInt(s);
        System.out.println(i);
    } catch (NumberFormatException e) {
        e.printStackTrace();
     }
   }
 }

выход:


По умолчанию метод parseInt () предполагает, что данная строка является целым числом с основанием 10. Кроме того, этот метод принимает другой аргумент для изменения системы счисления по умолчанию. Например, мы можем анализировать двоичные строки следующим образом

      public class StringToInt {
public static void main(String args[]) {
    String givenString = "101010";

    int result = Integer.parseInt(givenString, 2);
    System.out.println(result);
  }
}

выход:


Естественно, этот метод также можно использовать с любым другим основанием системы счисления, например 16 (шестнадцатеричный) или 8 (восьмеричный).

Integer.valueOf()

Другой вариант - использовать статический метод Integer.valueOf(), который возвращает экземпляр Integer.

      public class StringToInt {
public static void main(String args[]) {
    String s = "200";
    try {
        Integer i = Integer.valueOf(s);  
        System.out.println(i);  
    } catch (NumberFormatException e) {
        e.printStackTrace();
     }
  }
}

выход:

      200

Точно так же метод valueOf () также принимает настраиваемую систему счисления в качестве второго аргумента.

       public class StringToInt {
 public static void main(String args[]) {
    String s = "101010";
    try {
        Integer result = Integer.valueOf(givenString, 2);
        System.out.println(result);  
    } catch (NumberFormatException e) {
        e.printStackTrace();
     }
  }
}

выход:

      42

Integer.decode ()

Кроме того, Integer.decode () работает аналогично Integer.valueOf(), но также может принимать различные представления чисел.

      public class StringToInt {
 public static void main(String args[]) {
     String givenString = "1234";
    try {
        int result = Integer.decode(givenString);
        System.out.println(result);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
  }
}

выход:

      1234

NumberFormatException Случай

Если у вас нет чисел в строковом литерале, вызовы методов Integer.parseInt (), Integer.valueOf() и Integer.decode () вызывают исключение NumberFormatException.

Эта функция принимает любые типы параметров в качестве входных данных.

  • тогда попробуй конвертироватьtoString()
  • затем извлеките целое число через регулярное выражение
  • и безопасно преобразовать строку в int
          public int toInt(Object o) {

        // input param is an integer :|
        if (o instanceof Integer)
            return (int) o;

        // input param is (null) so return zero
        if (o == null)
            return 0;

        // input param is boolean, so false = 0 \ true = 1
        if (o instanceof Boolean)
            return Boolean.TRUE.equals(o) ? 1 : 0;

        // convert object to string
        String str = "0";
        if (o instanceof String) {
            str = (String) o;
        } else { 
            try {
                str = o.toString();
            } catch (Exception e) {}
        }

        // return zero if the string is empty
        if (str == "")
            return 0;

        // detect and export numbers from the string
        try {
            Pattern p = Pattern.compile("\\d+");
            Matcher m = p.matcher(str);
            if ( m.find() ) {
                str = m.group(0);
            } else { // string not contains any numbers
                str = "0";
            }
        } catch (Exception e) {
            str = "0";
        }
        
        // java stores integers in 32-bit, so can not store more than 10 digits
        if (str.length() > 19) {
            str = str.substring(0, 19);
        }

        // convert string to integer
        int result = 0;
        try {
            result = Integer.parseInt(str);
        } catch (Exception e) {}

        return result;
    }

Ты можешь измениться

      catch (Exception e) {}

к

      catch (Exception e) { e.printStackTrace(); }

чтобы показать более подробные данные об ошибках в logcat

Может обрабатывать такие входные данные, как:

  • false
  • ""
  • "00004"
  • " 51"
  • "74.6ab.cd"
  • "foo 654 bar"

Предупреждение

Эта функция изменится (строка)"ab2cd3ef4"к (интервал)234

Вы можете использовать метод parseInt

  String SrNumber="5790";
int extractNumber = Integer.parseInt(SrNumber);
System.out.println(extractNumber);//Result will be --5790

Использование Integer.parseInt(), это поможет вам в анализе вашего строкового значения в int.

Пример:

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

выход: 2017

Используя метод: Integer.parseInt(String s)

String s = "123";
int n = Integer.parseInt(s);

Пожалуйста, используйте NumberUtils для анализа целых чисел из строки.

  • Эта функция также может обрабатывать исключение, если заданная строка слишком длинная.
  • Мы также можем указать значения по умолчанию .

Вот пример кода.

      NumberUtils.toInt("00450");
NumberUtils.toInt("45464646545645400000");
NumberUtils.toInt("45464646545645400000", 0); // Where 0 is the default value.

output:
450
0
0

Я написал этот быстрый метод для анализа ввода строки в int или long. Это быстрее, чем текущий JDK 11 Integer.parseInt или Long.parseLong. Хотя вы спрашивали только int, я также включил длинный парсер. Парсер кода ниже требует, чтобы метод парсера был маленьким, чтобы он мог работать быстро. Альтернативная версия находится под тестовым кодом. Альтернативная версия довольно быстрая и не зависит от размера класса.

Этот класс проверяет наличие переполнения, и вы можете настроить код для адаптации к вашим потребностям. Пустая строка будет давать 0 с моим методом, но это намеренно. Вы можете изменить это, чтобы адаптировать ваш случай или использовать как есть.

Это только часть класса, где нужны parseInt и parseLong. Обратите внимание, что это касается только базовых 10 чисел.

Тестовый код для синтаксического анализатора int находится ниже кода ниже.

/*
 * 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 - kevin@fai.host.
 **/
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;
    }
}

Раздел тестового кода. Это должно занять около 200 секунд или около того.

// 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 */

Альтернативный метод, который также очень быстрый. Обратите внимание, что массив int pow не используется, но математическая оптимизация умножается на 10 путем сдвига битов.

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, 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;
}

Пользовательский алгоритм:

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;
}

другое решение:(используйте строковый метод charAt вместо преобразования строки в байтовый массив):

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;
}

Примеры:

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());
}

Используйте этот метод:

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;
}

Помимо всех этих ответов, я нашел один новый способ, хотя он использует внутренне Integer.parseInt(),

Используя

import javafx.util.converter.IntegerStringConverter;

new IntegerStringConverter().fromString("1234").intValue()

или же

new IntegerStringConverter().fromString("1234")

Хотя создание новых объектов обходится немного дороже, я просто хотел добавить, поскольку узнал новый способ.

Просто пройди javafx.util.StringConverter<T> class, он помогает преобразовать любое значение класса-оболочки в строку или наоборот.

Вы можете использовать их пути:

String stringNumber = "0123456789";

1- Используйте parseInt

try {
   int number = Integer.parseInt(stringNumber);
}catch (NumberFormatException e){
   // Handel exception, mybe has space or alphabet 
}

2- Используйте valueOf

try {
   int number = Integer.valueOf(stringNumber);
}catch (NumberFormatException e){
   // Handel exception, mybe has space or alphabet 
}

Некоторые из способов конвертировать String в Int следующие.

1. Integer.parseInt ()

Тест строки = "4568";
int new = Integer.parseInt (test);

2. Integer.valueOf ()

Тест строки = "4568";
int new = Integer.parseInt (test);

С участием Java 11, есть несколько способов преобразовать int к String тип :

1) Integer.parseInt()

      String str = "1234";
int result = Integer.parseInt(str);

2) Integer.valueOf()

      String str = "1234";
int result = Integer.valueOf(str).intValue();

3) Целочисленный конструктор

        String str = "1234";
  Integer result = new Integer(str);

4) Integer.decode

      String str = "1234";
int result = Integer.decode(str);

Вы можете использовать Integer.parseInt (str)

Например :

Строка str = "2";

int num = Intger.parseInt(строка);

Вам нужно позаботиться об исключении NumberFormatException в случае, если строка содержит недопустимые или нечисловые символы.

В качестве альтернативы вы можете использовать Integer.valueOf(). Это вернет Integer объект.

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

Выход:

10

Другие вопросы по тегам