1. ¿Cómo convertir una cadena (String) a un entero (int)?

A. Hay dos métodos:

  • 1、 int i = Integer.parseInt([String]);oi = Integer.parseInt([String],[int radix]);
  • 2、 int i = Integer.valueOf(my_str).intValue();

Nota: Los métodos para convertir cadenas a Double, Float, Long son prácticamente los mismos.

2. ¿Cómo convertir un entero (int) a una cadena (String)?

A. Hay tres métodos:

  • 1、String s = String.valueOf(i);
  • 2、String s = Integer.toString(i);
  • 3、String s = "" + i;

Nota: Los métodos para convertir Double, Float, Long a cadenas son prácticamente los mismos.

int -> String

int i=12345;

String s="";

Primer método:s=i+"";

Segundo método:s=String.valueOf(i);

¿Cuál es la diferencia entre estos dos métodos? ¿Tienen el mismo efecto? ¿Se pueden intercambiar en cualquier caso?

String -> int

s="12345";

int i;

Primer método:i=Integer.parseInt(s);

Segundo método:i=Integer.valueOf(s).intValue();

¿Cuál es la diferencia entre estos dos métodos? ¿Tienen el mismo efecto? ¿Se pueden intercambiar en cualquier caso?

La respuesta es la siguiente:

Primer método:s=i+""; //Se generarán dos objetos String

Segundo método:s=String.valueOf(i);//Se utiliza directamente el método estático de la clase String, solo se genera un objeto

Primer método:i=Integer.parseInt(s);//Se utiliza directamente el método estático, no se generan objetos adicionales, pero se lanzará una excepción

Segundo método:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) equivale a new Integer(Integer.parseInt(s)), también lanzará una excepción, pero generará un objeto adicional

Conversión de tipos de datos en Java

Este es un ejemplo sobre la conversión de tipos de datos en JAVA, para que todos lo usen como referencia de aprendizaje.

Ejemplo

import java.sql.Date; public class TypeChange { public TypeChange() { } //change the string type to the int type public static int stringToInt(String intstr) { Integer integer; integer = Integer.valueOf(intstr); return integer.intValue(); } //change int type to the string type public static String intToString(int value) { Integer integer = new Integer(value); return integer.toString(); } //change the string type to the float type public static float stringToFloat(String floatstr) { Float floatee; floatee = Float.valueOf(floatstr); return floatee.floatValue(); } //change the float type to the string type public static String floatToString(float value) { Float floatee = new Float(value); return floatee.toString(); } //change the string type to the sqlDate type public static java.sql.Date stringToDate(String dateStr) { return java.sql.Date.valueOf(dateStr); } //change the sqlDate type to the string type public static String dateToString(java.sql.Date datee) { return datee.toString(); } public static void main(String[] args) { java.sql.Date day ; day = TypeChange.stringToDate("2003-11-3"); String strday = TypeChange.dateToString(day); System.out.println(strday); } }