Type casting means converting a variable from one data type to another. Java supports both implicit (widening) and explicit (narrowing) conversions.
int x = 5;
double y = x; // Implicit
int z = (int) y; // ExplicitWidening happens automatically when converting from a smaller to a larger data type. No data is lost.
Narrowing must be done manually and may cause data loss.
boolean cannot be cast to/from other typeschar can be cast to/from int using ASCII codesObject casting allows you to convert one object type into another, either from a subclass to a superclass or vice versa. There are two types:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Bark");
}
}
Animal a = new Dog(); // Upcasting (implicit)
a.sound();Animal a = new Dog();
Dog d = (Dog) a; // Downcasting (explicit)
d.bark();⚠️ Downcasting must be used with caution. If the actual object is not of the subclass type, a ClassCastException will be thrown.
What will this output?
Hint: Narrowing truncates, it doesn't round.
Ask the AI if you need help understanding or want to dive deeper in any topic