¿Cómo convertir una cadena a un int en Java?


¿Cómo puedo convertir un String a un int en Java?

Mi Cadena contiene solo números, y quiero devolver el número que representa.

Por ejemplo, dada la cadena "1234" el resultado debería ser el número 1234.

Author: Peter Mortensen, 2011-04-07

30 answers

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

Consulte la Documentación de Java para obtener más información.

 3629
Author: Rob Hruska,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-10 09:27:34

Por ejemplo, aquí hay dos maneras:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

Hay una ligera diferencia entre estos métodos:

  • valueOf devuelve una instancia nueva o en caché de java.lang.Integer
  • parseInt devuelve primitivo int.

Lo mismo es para todos los casos: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

 606
Author: smas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 20:15:43

Bueno, un punto muy importante a considerar es que el analizador de enteros arroja NumberFormatException como se indica en Javadoc.

int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
      //Will Throw exception!
      //do something! anything to handle the exception.
}

try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
      //No problem this time, but still it is good practice to care about exceptions.
      //Never trust user input :)
      //Do something! Anything to handle the exception.
}

Es importante manejar esta excepción cuando se intenta obtener valores enteros de argumentos divididos o analizar algo dinámicamente.

 221
Author: Ali Akdurak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-16 23:35:36

Hazlo manualmente:

public static int strToInt( String str ){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    //Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;
    }

    //Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
    }

    if (isNeg)
        num = -num;
    return num;
}
 75
Author: Billz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-30 14:31:00

Actualmente estoy haciendo una tarea para la universidad, donde no puedo usar ciertas expresiones, como las anteriores, y mirando la tabla ASCII, me las arreglé para hacerlo. Es un código mucho más complejo, pero podría ayudar a otros que están restringidos como yo.

Lo primero que hay que hacer es recibir la entrada, en este caso, una cadena de dígitos; lo llamaré String number, y en este caso, lo ejemplificaré usando el número 12, por lo tanto String number = "12";

Otra limitación fue el hecho de que no se pudo usar ciclos repetitivos, por lo tanto, un ciclo for (que habría sido perfecto) tampoco se puede usar. Esto nos limita un poco, pero de nuevo, ese es el objetivo. Dado que solo necesitaba dos dígitos (tomando los dos últimos dígitos), un simple charAtlo resolvió:

 // 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);

Teniendo los códigos, solo tenemos que mirar hacia arriba en la tabla, y hacer los ajustes necesarios:

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

Ahora, ¿por qué doble? Bueno, por un paso realmente "raro". Actualmente tenemos dos dobles, 1 y 2, pero necesitamos convertirlo en 12, no hay ninguna operación matemática que podamos hacer.

Estamos dividiendo el último (lastdigit) por 10 de la manera 2/10 = 0.2 (de ahí por qué doble) de esta manera:

 lastdigit = lastdigit/10;

Esto es simplemente jugar con números. Estábamos convirtiendo el último dígito en un decimal. Pero ahora, mira lo que sucede:

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

Sin entrar demasiado en las matemáticas, simplemente estamos aislando unidades de los dígitos de un número. Verás, ya que solo consideramos 0-9, dividir por un múltiplo de 10 es como crear una "caja" donde guardarla(piense en cuando su maestro de primer grado le explicó lo que eran una unidad y cien). Así que:

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

Y ahí lo tienes. Usted convirtió una cadena de dígitos (en este caso, dos dígitos), en un entero compuesto de esos dos dígitos, teniendo en cuenta las siguientes limitaciones:

  • Sin ciclos repetitivos
  • No hay expresiones "Mágicas" como parseInt
 40
Author: Oak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 20:08:55

Una solución alternativa es usar Apache Commons ' NumberUtils:

int num = NumberUtils.toInt("1234");

La utilidad Apache es buena porque si la cadena es un formato de número no válido, siempre se devuelve 0. Por lo tanto, le ahorra el bloque try catch.

Apache NumberUtils API Version 3.4

 36
Author: Ryboflavin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-05 22:25:28

Integer.decode

También puedes usar public static Integer decode(String nm) throws NumberFormatException.

También funciona para la base 8 y 16:

// base 10
Integer.parseInt("12");     // 12 - int
Integer.valueOf("12");      // 12 - Integer
Integer.decode("12");       // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8);  // 10 - int
Integer.valueOf("12", 8);   // 10 - Integer
Integer.decode("012");      // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16);  // 18 - int
Integer.valueOf("12",16);   // 18 - Integer
Integer.decode("#12");      // 18 - Integer
Integer.decode("0x12");     // 18 - Integer
Integer.decode("0X12");     // 18 - Integer
// base 2
Integer.parseInt("11",2);   // 3 - int
Integer.valueOf("11",2);    // 3 - Integer

Si quieres obtener int en lugar de Integer puedes usar:

  1. Unboxing:

    int val = Integer.decode("12"); 
    
  2. intValue():

    Integer.decode("12").intValue();
    
 29
Author: ROMANIA_engineer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-07 00:42:49

Siempre que exista la más mínima posibilidad de que la Cadena dada no contenga un Entero, debe manejar este caso especial. Lamentablemente, los métodos Java estándar Integer::parseInt y Integer::valueOf lanzan un NumberFormatException para señalar este caso especial. Por lo tanto, debe usar excepciones para el control de flujo, que generalmente se considera un estilo de codificación incorrecto.

En mi opinión, este caso especial debe ser manejado devolviendo un Optional<Integer>. Dado que Java no ofrece este método, utilizo lo siguiente envoltura:

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

Uso:

// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));

Mientras que esto todavía está usando excepciones para el control de flujo internamente, el código de uso se vuelve muy limpio.

 23
Author: Stefan Dollase,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-04 03:20:37

Convertir una cadena a un int es más complicado que simplemente convertir un número. Usted tiene que pensar en los siguientes temas:

  • ¿La cadena solo contiene números 0-9?
  • ¿Qué pasa con -/+ ¿antes o después de la cuerda? ¿Es eso posible (refiriéndose a los números contables)?
  • ¿Qué pasa con MAX_-/MIN_INFINITY? ¿Qué pasará si la cadena es 9999999999999999999999999? ¿Puede la máquina tratar esta cadena como int?
 21
Author: Dennis Ahaus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-31 02:31:44

Podemos usar el método parseInt(String str) de la clase wrapper Integer para convertir un valor de cadena a un valor entero.

Por ejemplo:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

La clase Integer también proporciona el método valueOf(String str):

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

También podemos usar toInt(String strValue) de La clase de utilidad NumberUtils para la conversión:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
 20
Author: Giridhar Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-16 23:50:47

Uso Integer.parseInt(yourString)

Recuerda lo siguiente:

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

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

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

Integer.parseInt(" 1"); // Excepción (espacio en blanco)

Integer.parseInt("2147483648"); // Excepción (El entero está limitado a un valor máximo de 2,147,483,647)

Integer.parseInt("1.1"); // Excepción (. o , o lo que no está permitido)

Integer.parseInt(""); // Excepción (no 0 o algo)

Solo hay un tipo de excepción: NumberFormatException

 18
Author: Lukas Bauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-06 19:55:17

Tengo una solución, pero no sé qué tan efectiva es. Pero funciona bien, y creo que podrías mejorarlo. Por otro lado, hice un par de pruebas con JUnit que paso correctamente. Adjunté la función y la prueba:

static public Integer str2Int(String str) {
    Integer result = null;
    if (null == str || 0 == str.length()) {
        return null;
    }
    try {
        result = Integer.parseInt(str);
    } 
    catch (NumberFormatException e) {
        String negativeMode = "";
        if(str.indexOf('-') != -1)
            negativeMode = "-";
        str = str.replaceAll("-", "" );
        if (str.indexOf('.') != -1) {
            str = str.substring(0, str.indexOf('.'));
            if (str.length() == 0) {
                return (Integer)0;
            }
        }
        String strNum = str.replaceAll("[^\\d]", "" );
        if (0 == strNum.length()) {
            return null;
        }
        result = Integer.parseInt(negativeMode + strNum);
    }
    return result;
}

Probando con JUnit:

@Test
public void testStr2Int() {
    assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
    assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
    assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
    assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
    assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
    assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
    assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
    assertEquals("Not
     is numeric", null, Helper.str2Int("czv.,xcvsa"));
    /**
     * Dynamic test
     */
    for(Integer num = 0; num < 1000; num++) {
        for(int spaces = 1; spaces < 6; spaces++) {
            String numStr = String.format("%0"+spaces+"d", num);
            Integer numNeg = num * -1;
            assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
            assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
        }
    }
}
 17
Author: fitorec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-29 08:36:51

Métodos para hacer eso:

 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)

Entero.valueOf produce un objeto entero, todos los demás métodos-primitive int.

Los últimos 2 métodos de commons-lang3 y un gran artículo sobre la conversión aquí.

 17
Author: Dmytro Shvechikov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 19:45:55

Solo por diversión: Puedes usar Java 8 Optional para convertir un String en un Integer:

String str = "123";
Integer value = Optional.of(str).map(Integer::valueOf).get();
// Will return the integer value of the specified string, or it
// will throw an NPE when str is null.

value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
// Will do the same as the code above, except it will return -1
// when srt is null, instead of throwing an NPE.

Aquí solo combinamos Integer.valueOf y Optinal. Probablemente haya situaciones en las que esto sea útil, por ejemplo, cuando desea evitar comprobaciones nulas. El código pre Java 8 se verá así:

Integer value = (str == null) ? -1 : Integer.parseInt(str);
 16
Author: Anton Balaniuc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 20:13:19

Guava tiene TryParse (String) , que devuelve null si la cadena no se puede analizar, por ejemplo:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}
 14
Author: Vitalii Fedorenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-06 17:56:29

También puede comenzar eliminando todos los caracteres no numéricos y luego analizando el int:

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

Pero tenga en cuenta que esto solo funciona para números no negativos.

 12
Author: Thijser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 19:48:23

Aparte de estas respuestas anteriores, me gustaría agregar varias funciones:

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

Y aquí están los resultados mientras los ejecuta:

  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
  }
 10
Author: nxhoaf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-12 14:27:11

Puede usar new Scanner("1244").nextInt(). O pregunte si incluso existe un int: new Scanner("1244").hasNextInt()

 9
Author: Christian Ullenboom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-28 20:36:40

También puede usar este código, con algunas precauciones.

  • Opción #1: Maneje la excepción explícitamente, por ejemplo, mostrando un diálogo de mensaje y luego detenga la ejecución del flujo de trabajo actual. Por ejemplo:

    try
        {
            String stringValue = "1234";
    
            // From String to Integer
            int integerValue = Integer.valueOf(stringValue);
    
            // Or
            int integerValue = Integer.ParseInt(stringValue);
    
            // Now from integer to back into string
            stringValue = String.valueOf(integerValue);
        }
    catch (NumberFormatException ex) {
        //JOptionPane.showMessageDialog(frame, "Invalid input string!");
        System.out.println("Invalid input string!");
        return;
    }
    
  • Opción #2: Restablecer la variable afectada si el flujo de ejecución puede continuar en caso de una excepción. Por ejemplo, con algunas modificaciones en el bloque catch

    catch (NumberFormatException ex) {
        integerValue = 0;
    }
    

Usando una constante de cadena para la comparación o cualquier tipo de la computación siempre es una buena idea, porque una constante nunca devuelve un valor nulo.

 8
Author: manikant gautam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-05 04:28:17

Como se mencionó Apache Commons NumberUtils puede hacerlo. Que devuelven 0 si no puede convertir string a int.

También puede definir su propio valor predeterminado.

NumberUtils.toInt(String str, int defaultValue)

Ejemplo:

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; 
 8
Author: Alireza Fattahi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 05:41:55

En competiciones de programación, donde se le asegura que el número siempre será un entero válido, entonces puede escribir su propio método para analizar la entrada. Esto saltará todo el código relacionado con la validación (ya que no necesita nada de eso) y será un poco más eficiente.

  1. Para un entero positivo válido:

    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. Para enteros positivos y negativos:

    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. Si espera un espacio en blanco antes o después de estos números, entonces asegúrese de hacer un str = str.trim() antes de procesar más.

 8
Author: Raman Sahasi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-24 05:36:19

Simplemente puedes probar esto:

  • Use Integer.parseInt(your_string); para convertir a String a int
  • Use Double.parseDouble(your_string); para convertir a String a double

Ejemplo

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
 7
Author: Vishal Yadav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 12:12:17

Para la cadena normal puede usar:

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

Para String builder y String buffer puedes usar:

Integer.parseInt(myBuilderOrBuffer.toString());
 6
Author: Aditya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-18 07:07:24
int foo=Integer.parseInt("1234");

Asegúrese de que no haya datos no numéricos en la cadena.

 6
Author: iKing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-08 22:24:54

Aquí vamos

String str="1234";
int number = Integer.parseInt(str);
print number;//1234
 6
Author: Shivanandam Sirmarigari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-09 15:05:12

Estoy un poco sorprendido de que nadie no mencionó el constructor Entero que toma String como parámetro.
Entonces, aquí está:

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

Java 8-Integer (String) .

Por supuesto, el constructor devolverá el tipo Integer, y la operación unboxing convierte el valor a int.


Es importante mencionar
Este constructor llama al método parseInt.

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}
 6
Author: djm.im,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-09 14:56:52

Un método es parseInt (Cadena) devuelve un int primitivo

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

El segundo método es valueOf(String) devuelve un nuevo objeto Integer ().

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
 5
Author: Pankaj Mandale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-12 14:25:51

Utilice Entero.parseInt () y ponerlo dentro de un bloque try...catch para manejar cualquier error en caso de que se introduzca un carácter no numérico, por ejemplo,

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);
    }
 }
 5
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-21 22:33:28

Este es un programa completo con todas las condiciones positivas, negativas sin usar la biblioteca

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;
     }
    }
 4
Author: Anup Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 06:53:39

Por cierto, tenga en cuenta que si la cadena es null, la llamada:

int i = Integer.parseInt(null);

Lanza NumberFormatException, no NullPointerException.

 3
Author: Pavel Molchanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-20 21:26:24