Numeric primitive casting

suggest change

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 fractional part is discarded. That is truncation toward zero, not rounding down: (int) -1.9 is -1.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents