Section 1: Numeric Primitive Casting

Implicit Casting

Numeric primitives can be implicitly cast when the source type has a 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;

In the above example, the smaller data types (byte, short, int) are implicitly cast to larger data types (short, int, long, float, double) without explicit type conversion.

Explicit Casting

Explicit casting is necessary when the source type has a 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;

Here, explicit casting is performed to convert a larger data type (double, float, long, int, short) to a smaller data type (float, long, int, short, byte).

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

Section 2: Basic Numeric Promotion

Numeric promotion automatically occurs in certain situations.

static void testNumericPromotion() {
 char char1 = 1, char2 = 2;
 short short1 = 1, short2 = 2;
 int int1 = 1, int2 = 2;
 float float1 = 1.0f, float2 = 2.0f;

 // char1 = char1 + char2; // Error: Cannot convert from int to char;
 // short1 = short1 + short2; // Error: Cannot convert from int to short;
 int1 = char1 + char2; // char is promoted to int.
 int1 = short1 + short2; // short is promoted to int.
 int1 = char1 + short2; // both char and short promoted to int.
 float1 = short1 + float2; // short is promoted to float.
 int1 = int1 + int2; // int is unchanged.
}

In the testNumericPromotion method, numeric promotion is demonstrated with different data types. For example, when adding char1 and char2, they are promoted to int.


Section 3: Non-Numeric Primitive Casting

Section 4: Object Casting