EMZETT.
Login

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 matching

4. Boxing

Integer boxed = 5;     // int → Integer (automatic, autoboxing)
int plain = boxed;     // unboxing (NullPointerException if boxed is null)
  • Rounding trap: (int) 2.9999999 is 2. int / int gives an integer: 5 / 2 == 2. Make one side a double: 5 / 2.0 == 2.5.
  • Integer overflow: int covers ±2.1 billion. Use long for larger values. Math.addExact throws an exception on overflow.
  • Characters: (int) 'A' is 65, (char) 66 is 'B'.
  • Date and time: LocalDate.parse("2026-10-13"), DateTimeFormatter for custom formats.
  • Data formats: JSON ↔ object (Jackson, Gson) and text ↔ bytes (getBytes(StandardCharsets.UTF_8)) are conversions too.
  • Precision: For money use BigDecimal, not double.

See also: Type casting, Wrapper classes, Numbers and strings