Conversions, Casting, Autoboxing, and Unboxing

Java performs some conversions automatically when they are safe, such as widening int to long. Narrowing conversions require an explicit cast and can lose information.

int n = 10;
long big = n;
int smaller = (int) big;

Integer boxed = n;
int value = boxed;

Boxing is convenient but creates object values when an object representation is needed. It can also introduce NullPointerException during unboxing if a wrapper is null.

Numeric promotion can produce surprising results. 5 / 2 is 2 because both operands are integers; 5 / 2.0 is 2.5.

Beware unboxing

A nullable Integer is not interchangeable with an int; unboxing null throws NullPointerException.

Key Takeaways
  • Widening conversions generally preserve the value.
  • Narrowing casts may truncate or overflow.
  • Autoboxing is convenient but does not remove allocation and nullability concerns.