1. Contenidos
1.1 Concepto de conversión de tipos
En Java, una conversión de tipo (type conversion) es el proceso de transformar un valor de un tipo de dato a otro. Esto es necesario cuando asignamos una variable de un tipo a otra de distinto tipo, o cuando combinamos diferentes tipos en una expresión.
Existen dos categorías principales:
- Conversiones implícitas (widening o promoción): ocurren automáticamente cuando no hay pérdida de datos.
- Conversiones explícitas (narrowing o casting): requieren una sintaxis especial porque puede haber pérdida de precisión o información.
Importante: Java es un lenguaje fuertemente tipado. No permite operaciones entre tipos incompatibles sin una conversión adecuada.
1.2 Conversiones implícitas (promoción automática)
Ocurren cuando el tipo destino tiene mayor rango o capacidad que el tipo origen. No se necesita sintaxis especial y no hay pérdida de datos.
Jerarquía de promoción numérica (de menor a mayor capacidad):
byte → short → int → long → float → double
char → int
Ejemplos de conversiones implícitas:
// De int a double (implícita, sin pérdida)
int numeroEntero = 42;
double numeroDecimal = numeroEntero; // 42.0
// De char a int (implícita, obtiene el valor Unicode)
char letra = 'A';
int codigoAscii = letra; // 65
// En expresiones mixtas: int + double → double
int a = 10;
double b = 3.5;
double resultado = a + b; // 13.5 (a se promueve a double)
Regla: En operaciones aritméticas, Java promueve automáticamente los tipos más pequeños a int como mínimo. Los tipos byte, short y char siempre se promueven a int antes de operar.
1.3 Conversiones explícitas (casting)
El casting es necesario cuando el tipo destino tiene menor capacidad o rango que el tipo origen. Puede haber pérdida de datos o precisión. La sintaxis es: (tipo_destino) valor
Casting entre tipos numéricos:
// De double a int (pérdida de decimales)
double pi = 3.1416;
int entero = (int) pi; // 3 (se trunca, no redondea)
// De long a byte (desbordamiento)
long numeroGrande = 300;
byte pequeno = (byte) numeroGrande; // 44 (desbordamiento: 300 - 256 = 44)
// De int a char (conversión a carácter)
int codigo = 65;
char caracter = (char) codigo; // 'A'
Casting en expresiones:
int x = 7, y = 2;
double divisionExacta = (double) x / y; // 3.5 (casting de x a double)
// Sin casting: x / y daría 3 (división entera)
Precaución: El casting entre tipos numéricos puede causar pérdida de datos o resultados inesperados. Siempre verificar los rangos.
1.4 Conversiones usando Wrappers (Integer, Double, Float, Boolean)
Las clases wrapper permiten convertir entre tipos primitivos y String, así como entre distintos tipos numéricos mediante métodos estáticos.
Conversiones String ↔ tipos primitivos:
// String a Integer
String textoNumero = "123";
Integer entero = Integer.parseInt(textoNumero); // 123
Integer enteroWrapper = Integer.valueOf(textoNumero);
// String a Double
String textoDecimal = "45.67";
Double decimal = Double.parseDouble(textoDecimal); // 45.67
// String a Float
Float flotante = Float.parseFloat("3.14f"); // 3.14
// String a Boolean (case insensitive, "true" → true, cualquier otro → false)
String textoBool = "true";
Boolean bool = Boolean.parseBoolean(textoBool); // true
String textoFalso = "TRUE";
Boolean bool2 = Boolean.parseBoolean(textoFalso); // true (case insensitive)
String textoInvalido = "si";
Boolean bool3 = Boolean.parseBoolean(textoInvalido); // false
// Primitivo a String
String strEntero = Integer.toString(456); // "456"
String strDouble = Double.toString(78.9); // "78.9"
String strBool = Boolean.toString(true); // "true"
Conversiones entre tipos numéricos con wrappers:
// De Integer a Double (necesita casting o métodos)
Integer entero = 100;
Integer valor = entero; // unboxing automático
Double doble = entero.doubleValue(); // 100.0
// De Double a Integer (con pérdida)
Double decimalObj = 99.99;
Integer enteroDesdeDouble = decimalObj.intValue(); // 99 (truncado)
// De Float a Integer
Float floatObj = 25.7f;
Integer desdeFloat = floatObj.intValue(); // 25
1.5 Conversión de Boolean a Integer (con operador ternario)
No existe un método directo para convertir boolean a int, pero podemos usar el operador ternario para lograr esta conversión de forma elegante y segura.
// Conversión boolean → int: true = 1, false = 0
Boolean estaActivo = true;
Integer valorInt = estaActivo ? 1 : 0; // valorInt = 1
Boolean esMayor = 10 > 5;
Integer resultadoComparacion = esMayor ? 1 : 0; // 1
// También se puede invertir: int → boolean (con operador ternario)
Integer estado = 1;
Boolean activo = (estado == 1) ? true : false; // true
Ejemplo completo de conversión Boolean ↔ Integer:
public class BooleanAInteger {
public static void main(String[] args) {
// Boolean a Integer
Boolean flag1 = true;
Boolean flag2 = false;
Integer entero1 = flag1 ? 1 : 0; // 1
Integer entero2 = flag2 ? 1 : 0; // 0
System.out.println("true → " + entero1);
System.out.println("false → " + entero2);
// Integer a Boolean (conversión inversa)
Integer valor = 1;
Boolean booleano = (valor != 0) ? true : false; // true
// También se puede simplificar (en Java, 0 es false, distinto de 0 es true)
Boolean simplificado = (valor != 0); // true
}
}
Importante: El operador ternario es la forma más limpia de convertir Boolean a Integer porque es una línea, autoexplicativa y evita estructuras if-else innecesarias.
1.6 Tabla resumen de conversiones comunes
| Conversión | Método / Sintaxis | Ejemplo | Resultado |
| String → Integer | Integer.parseInt(str) | Integer.parseInt("42") | 42 |
| String → Double | Double.parseDouble(str) | Double.parseDouble("3.14") | 3.14 |
| String → Boolean | Boolean.parseBoolean(str) | Boolean.parseBoolean("true") | true |
| Integer → String | Integer.toString(n) | Integer.toString(100) | "100" |
| double → Integer (cast) | (int) d | (int) 9.99 | 9 |
| Double → Integer (wrapper) | Double.valueOf(d).intValue() | new Double(9.99).intValue() | 9 |
| Boolean → Integer | b ? 1 : 0 | true ? 1 : 0 | 1 |
| Integer → Boolean | n != 0 | 1 != 0 | true |
| Integer → Double | intVar.doubleValue() | Integer.valueOf(5).doubleValue() | 5.0 |
| Float → Integer | floatVar.intValue() | Float.valueOf(12.7f).intValue() | 12 |