Type Casting and Conversion

Site Admin · 11 Sep 2026 · 12 views

Why Conversion Matters

When you mix values of different number types, Java must convert between them. Some conversions happen automatically; others need an explicit cast.

Implicit Conversion (Widening)

When you assign a smaller type to a larger one, Java converts automatically because no data can be lost.

int i = 100;
long l = i;      // int fits into long - automatic
float f = l;
double d = f;    // chain of widening conversions

The widening order is: byte < short < int < long < float < double.

Explicit Conversion (Narrowing)

Going the other way may lose information, so Java demands an explicit cast. You are telling the compiler you accept the risk.

double price = 49.99;
int rounded = (int) price;   // 49, the fraction is dropped
long big = 1_000_000_000L;
int smaller = (int) big;     // may overflow silently

Numeric Promotion in Expressions

In arithmetic, byte, short and char are promoted to int before the operation runs.

byte a = 10;
byte b = 20;
byte c = (byte) (a + b); // a+b is already an int, cast back needed
int sum = a + b;         // fine without cast

Converting Between String and Numbers

String s = "42";
int n = Integer.parseInt(s);      // "42" -> 42
double d = Double.parseDouble("3.5");

String back = String.valueOf(n);          // 42 -> "42"
String also = Integer.toString(n);

Key Points

  • Widening converts automatically; narrowing requires a cast.
  • Casting to a smaller type can truncate or overflow values.
  • Use Integer.parseInt style methods for string-to-number conversion.
Share this post:

Comments (0)

Please login or register to comment.