Java Language Numeric primitive casting


Example

Numeric primitives can be cast in two ways. Implicit casting happens when the source type has smaller range than the target type.

//Implicit casting
byte byteVar = 42;
short shortVar = byteVar;
int intVar = shortVar;
long longVar = intvar;
float floatVar = longVar;
double doubleVar = floatVar;

Explicit casting has to be done when the source type has larger range than the target type.

//Explicit casting
double doubleVar = 42.0d;
float floatVar = (float) doubleVar;
long longVar = (long) floatVar;
int intVar = (int) longVar;
short shortVar = (short) intVar;
byte byteVar = (byte) shortVar;

When casting floating point primitives (float, double) to whole number primitives, the number is rounded down.