Type conversion in Java (code conversions)
In short: Type conversion means transferring a value from one data type to another: between numbers (int ↔ double), between text and number ("42" ↔ 42) and between object types.
In more detail: Java is strictly typed. Some conversions the compiler does itself (safe); others must be requested explicitly (with risk). Text and numbers are converted with methods, not with casts.
In Depth
1. Numbers: implicit (widening) and explicit (narrowing)
int i = 5;
double d = i; // automatic: int → double (no loss)
long l = i; // automatic
double pi = 3.99;
int k = (int) pi; // cast needed: 3 (decimals are cut off, not rounded)
int r = (int) Math.round(pi); // 4 (rounding)
byte b = (byte) 200; // -56 (overflow!)Order of widening: byte → short → int → long → float → double. Going backwards needs a cast and can lose information.
2. Text ↔ number
int a = Integer.parseInt("42"); // text → int
double x = Double.parseDouble("3.14"); // dot as decimal separator
String s = String.valueOf(42); // number → text
String t = "" + 42; // likewise
// Integer.parseInt("abc") throws NumberFormatException → catch it!3. Objects: upcast and downcast
Animal a = new Dog(); // upcast: automatic
Dog d = (Dog) a; // downcast: cast, can fail
if (a instanceof Dog dog) { dog.bark(); } // safe with pattern matching4. Boxing
Integer boxed = 5; // int → Integer (automatic, autoboxing)
int plain = boxed; // unboxing (NullPointerException if boxed is null)- Rounding trap:
(int) 2.9999999is 2.int / intgives an integer:5 / 2 == 2. Make one side adouble:5 / 2.0 == 2.5. - Integer overflow:
intcovers ±2.1 billion. Uselongfor larger values.Math.addExactthrows an exception on overflow. - Characters:
(int) 'A'is 65,(char) 66is'B'. - Date and time:
LocalDate.parse("2026-10-13"),DateTimeFormatterfor custom formats. - Data formats: JSON ↔ object (Jackson, Gson) and text ↔ bytes (
getBytes(StandardCharsets.UTF_8)) are conversions too. - Precision: For money use
BigDecimal, notdouble.
See also: Type casting, Wrapper classes, Numbers and strings