Junior
Explain type casting in Java, what is type downcasting and upcasting?
sobes.tech AI
Answer from AI
Type casting in Java is the conversion of a value from one data type to another.
There are two types of casting:
- Widening Conversion or upcasting. It occurs automatically if the type to which the value is being converted can hold all possible values of the original type. No data loss occurs.
Examples:
int->longfloat->double
// Example of widening conversion
int ival = 10;
long lval = ival; // Automatic promotion of int to long
- Narrowing Conversion or downcasting. It requires explicit indication in the code using the cast operator
(type). It can lead to data loss if the value of the original type exceeds the range of the target type.
Examples:
long->intdouble->float
// Example of narrowing conversion
long lval = 1000L;
int ival = (int) lval; // Explicit narrowing of long to int. Without explicit cast - compile error.
double dval = 123.45;
int intFromDouble = (int) dval; // Loss of fractional part and narrowing to int
Type casting of reference types:
- Upcasting (Subtype to Supertype): occurs automatically, an instance of a subclass can be assigned to a variable of a superclass type.
- Downcasting (Supertype to Subtype): requires explicit cast and runtime type check (throws
ClassCastException).
// Example of reference type casting
class Animal {}
class Dog extends Animal {}
Animal animal = new Dog(); // Upcasting: Dog to Animal (automatic)
Dog dog = (Dog) animal; // Downcasting: Animal to Dog (requires explicit cast)
// Dangerous: may throw ClassCastException
Animal anotherAnimal = new Animal();
// Dog anotherDog = (Dog) anotherAnimal; // Runtime error, Animal is not a Dog