Type Casting in Java

Short Answer:
Type casting in Java means converting one data type into another data type.

Detailed Explanation:
Java supports two types of casting:

  • Primitive Type Casting
  • Object Type Casting

Casting can be automatic (implicit) or manual (explicit).


1. Primitive Type Casting

Short: Converting one primitive type to another.

a) Widening Casting (Implicit)

Smaller type → Larger type (Automatic conversion).

int num = 10;
double d = num;   // int → double

No data loss. Done automatically by JVM.

b) Narrowing Casting (Explicit)

Larger type → Smaller type (Manual conversion required).

double d = 10.75;
int num = (int) d;   // double → int

Data loss may occur (decimal part removed).


2. Object Type Casting

Short: Converting parent reference to child or vice versa.

a) Upcasting (Implicit)

class Animal {}
class Dog extends Animal {}

Animal a = new Dog();  // Upcasting

Child object treated as Parent reference. Done automatically.

b) Downcasting (Explicit)

Dog d = (Dog) a;   // Downcasting

Parent reference converted back to Child. May throw ClassCastException if incorrect.


Important Interview Points

  • Widening is safe, narrowing may cause data loss.
  • Upcasting is safe and automatic.
  • Downcasting requires explicit casting.
  • Use instanceof before downcasting to avoid runtime exception.

0 comments

Leave a comment