Java Language Type Conversion Numeric primitive casting

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Java Language Question?