πŸš€ Type Casting in Java – Complete Detailed Guide

Introduction

In Java programming, data types play a crucial role. Sometimes, we need to convert one data type into another β€” either to perform calculations, store values, or pass data to methods.

This conversion process is called Type Casting 🎯

Understanding type casting properly is very important because:

  • It prevents data loss
  • It avoids compile-time errors
  • It helps in working with different data types
  • It is heavily used in real-world applications

Let’s understand everything step-by-step.


🧠 What is Type Casting?

Type Casting is the process of converting one data type into another.

In Java, type casting is divided into:

1️⃣ Primitive Type Casting
2️⃣ Object Type Casting


πŸ“˜ 1. Primitive Type Casting

Primitive casting happens between basic data types like:

  • byte
  • short
  • int
  • long
  • float
  • double
  • char

Primitive casting is of two types:

  • Widening (Implicit Casting)
  • Narrowing (Explicit Casting)

🟒 Widening Casting (Implicit Casting)

Also called:

βœ” Automatic casting
βœ” Upcasting (for primitives)

Happens when:

  • Smaller data type β†’ Larger data type
  • No data loss

Order of widening:

byte β†’ short β†’ int β†’ long β†’ float β†’ double

🟒 Example 1: Widening Casting

public class WideningDemo {
public static void main(String[] args) { int num = 100;
double d = num; // Automatic casting System.out.println("Integer value: " + num);
System.out.println("Converted to double: " + d);
}
}

🧠 Explanation

  • num is int
  • int is converted automatically to double
  • No cast operator needed
  • No data loss

πŸ”΄ Narrowing Casting (Explicit Casting)

Also called:

βœ” Manual casting
βœ” Downcasting (for primitives)

Happens when:

  • Larger data type β†’ Smaller data type
  • Possible data loss

You must use cast operator.


🟒 Example 2: Narrowing Casting

public class NarrowingDemo {
public static void main(String[] args) { double d = 10.75;
int num = (int) d; // Explicit casting System.out.println("Double value: " + d);
System.out.println("Converted to int: " + num);
}
}

🧠 Explanation

  • Double contains decimal
  • Casting to int removes decimal part
  • Output: 10
  • Data loss occurs

⚠ Important Data Loss Example

public class DataLossDemo {
public static void main(String[] args) { int num = 130;
byte b = (byte) num; System.out.println(b);
}
}

🧠 Why Output Is Strange?

  • byte range: -128 to 127
  • 130 exceeds byte range
  • Overflow happens

This causes unexpected output.


🎯 Casting Between int and char

public class CharCasting {
public static void main(String[] args) { int num = 65;
char ch = (char) num; System.out.println(ch);
}
}

Output:

A

Because ASCII value of 65 is β€˜A’.


πŸ“˜ 2. Object Type Casting

Object casting happens in OOP when:

  • One class reference is converted into another class reference

Object casting is of two types:

1️⃣ Upcasting
2️⃣ Downcasting


🟒 Upcasting

Converting child class object to parent class reference.

Automatically done by Java.


🟒 Example 3: Upcasting

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}public class UpcastingDemo {
public static void main(String[] args) { Animal a = new Dog(); // Upcasting a.sound();
}
}

🧠 Explanation

  • Dog object stored in Animal reference
  • Only parent methods accessible
  • Safe casting

πŸ”΄ Downcasting

Converting parent reference to child reference.

Requires explicit cast.


🟒 Example 4: Downcasting

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}public class DowncastingDemo {
public static void main(String[] args) { Animal a = new Dog();
Dog d = (Dog) a; // Downcasting d.bark();
}
}

🧠 Explanation

  • Parent reference converted back to child
  • Explicit cast required
  • Safe because object is originally Dog

❌ Dangerous Downcasting Example

Animal a = new Animal();
Dog d = (Dog) a; // Runtime error

This causes:

ClassCastException

🧠 How To Avoid Runtime Error?

Use:

if(a instanceof Dog) {
Dog d = (Dog) a;
}

πŸ“Œ Primitive vs Object Casting

Primitive CastingObject Casting
Between data typesBetween class references
int β†’ doubleChild β†’ Parent
Uses type operatorUses type operator
Compile-time checkRuntime check

πŸ”₯ Common Mistakes

❌ Forgetting cast operator

double d = 10.5;
int x = d; // Error

❌ Ignoring data loss

int x = (int) 9.9; // 9, not 10

❌ Unsafe downcasting

Parent p = new Parent();
Child c = (Child) p; // Runtime error

🧠 Interview Questions

βœ” Difference between widening and narrowing
βœ” What happens during overflow?
βœ” What is upcasting and downcasting?
βœ” What is ClassCastException?
βœ” Why explicit casting required in narrowing?


πŸš€ Real-World Use Cases

  • Parsing data
  • Numeric calculations
  • Working with generics
  • Polymorphism
  • Memory optimization

🎯 Quick Summary

βœ” Widening β†’ Automatic, Safe
βœ” Narrowing β†’ Manual, Risky
βœ” Upcasting β†’ Automatic
βœ” Downcasting β†’ Manual, Risky
βœ” Always check before downcasting


βœ… Conclusion

Type Casting is a fundamental concept in Java that ensures flexibility when working with different data types and objects πŸš€

Understanding:

  • Primitive casting
  • Widening & narrowing
  • Upcasting & downcasting
  • Data loss
  • Runtime errors

Helps you write safer and more efficient programs.

Mastering type casting strengthens your understanding of Java’s type system and object-oriented design.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *