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)