DEV Community

realNameHidden
realNameHidden

Posted on

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


Enter fullscreen mode Exit fullscreen mode

(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

Enter fullscreen mode Exit fullscreen mode

🔹 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)

Enter fullscreen mode Exit fullscreen mode

(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)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)