En este artículo vamos a discutir la conversión de String a int (tipo primitivo) y tipo de objeto (envoltura) Integer. Hay muchas formas de hacerlo en Java.
Cómo convertir String a int en Java
Aquí hay un par de formas de convertir cadenas a int, Java permite hacerlo usandoparseInt()
y valueOf()
métodos.
-
Cadena Java a int usando Integer.parseInt(String)
parseInt
es un método estático de la clase Integer que devuelve un objeto entero que representa el parámetro String especificado .Sintaxis:
public static int parseInt(String str) throws NumberFormatException
O
public static int parseInt(String str, int radix) throws NumberFormatException
¿Dónde
str
está una cadena que necesita convertir yradix
es una base del número analizado?Convertir cadena a entero, ejemplo de Java usando parseInt()
public class Demo2 { // convert string to int java public static void main(String args[]) { String str = "111"; int num1 = Integer.parseInt(str); System.out.println("parseInt of the String = " + num1); int num2 = Integer.parseInt(str, 2);//binary number System.out.println("parseInt of the String with radix parameter = " + num2); } }
La salida es:
parseInt of the String = 111 parseInt of the String with radix parameter = 7
Aquí tenemos 111 en la primera variante y 7 en la segunda. 7 es una forma decimal de binario 111.
-
Convertir usando Integer.valueOf(String)
Integer.valueOf(String s) es un método Java de la clase Integer. Devuelve una interpretación decimal entera de un objeto String, por lo que se utiliza para convertir String a Integer.
Sintaxis:
public static Integer valueOf(String str) Example Java String to Integer using valueOf method: public class Demo2 { // java convert string to int using valueOf() String myString = "578"; int parNum = Integer.valueOf(myString); System.out.println("Integer from String using valueOf() = " + parNum); } }
Producción:
Integer from String using valueOf() = 578