Explicit casting is when you manually convert a larger data type into a smaller one. This can lead to data loss, so Java doesn’t do it automatically.

Order

Requires manual cast - may lose precision or overflow
double β†’ float β†’ long β†’ int β†’ short β†’ byte

Example

double d = 9.55;
int x = (int) d; // double β†’ int (manual cast)
System.out.println(x); // 9 (decimal part lost)
Risk of data loss!
int big = 130;
byte small = (byte) big;
System.out.println(small); // -126
 
// Byte range: -128 to 127
// Value wraps around if out of range

Tip

Use explicit casting when:

  • You’re going from larger β†’ smaller.
  • You understand and accept potential data loss.

Parent: _Casting & Types