There are two types of casting, casting between primitive numeric types and casting between object references.
Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values.
Casting between object references is used to refer to an object by a compatible class, interface, or arraytype reference.
In Java, casting refers to the process of explicitly converting a value from one data type to another. There are two types of casting in Java:
- Widening (Implicit) Casting: This occurs when you convert a smaller data type to a larger data type, and Java does it automatically without any explicit casting needed. For example, converting an
int
to along
or afloat
to adouble
is a widening conversion.javaint intValue = 10;
long longValue = intValue; // Widening (implicit) casting
- Narrowing (Explicit) Casting: This occurs when you convert a larger data type to a smaller data type, and it requires explicit casting because there is a possibility of losing data. For example, converting a
double
to anint
requires explicit casting.javadouble doubleValue = 10.5;
int intValue = (int) doubleValue; // Narrowing (explicit) casting
It’s important to note that narrowing casting may lead to loss of information if the value being cast cannot be represented accurately in the target data type. Therefore, it should be done carefully, and programmers need to be aware of potential data loss.