What Are Two Types of Casting in Java?
๐น 1. Primitive Casting
This is casting between primitive data types (like int, double, float, etc.).
(a) Widening (Implicit) Casting
Happens automatically when converting a smaller type to a larger type.
Safe because thereโs no data loss.
โ Example
int x = 10;
double y = x; // int โ double (automatic widening)
System.out.println(y); // 10.0
(b) Narrowing (Explicit) Casting
Needs explicit conversion using (type).
Risk of data loss.
โ Example:
double d = 9.8;
int i = (int) d; // double โ int (explicit narrowing)
System.out.println(i); // 9
๐น 2. Reference Casting (Object Casting)
This is casting between objects (classes/interfaces) in the inheritance hierarchy.
(a) Upcasting (Implicit)
Converting subclass โ superclass.
Always safe.
โ Example:
class Animal {}
class Dog extends Animal {}
Animal a = new Dog(); // Upcasting (automatic)
(b) Downcasting (Explicit)
Converting superclass โ subclass.
Must be done explicitly.
Can throw ClassCastException if the object isnโt actually of that subclass.
โ Example:
Animal a = new Dog();
Dog d = (Dog) a; // Downcasting (explicit)