Java Type Casting & Conversion - In-depth Guide

Introduction

Java me Type Casting aur Type Conversion do important concepts hain jo data types ke beech value transfer karne ke liye use hote hain. Type Casting me value ko explicitly ek type se dusre type me convert kiya jata hai jabki Type Conversion automatically hoti hai.

Type Casting: Detailed Explanation

Type Casting ek manual conversion process hai jisme aap programmer ke dwara explicitly value ka type badalna hota hai. Ye important hota hai jab aapko kisi bade data type ko chhote data type me convert karna ho, jaise double se int.

Syntax:

targetType variable = (targetType) value;

Example:

double price = 99.99;
int intPrice = (int) price;  // Fractional part truncate ho gaya, intPrice = 99
System.out.println("Price as int: " + intPrice);

Type Casting me data truncation ya data loss ho sakta hai, isliye careful rahna chahiye.

Type Conversion (Type Promotion): Detailed Explanation

Type Conversion automatically JVM ya compiler karta hai jab ek chhote data type ko bade data type me convert karna ho, jaise int se double. Is process me data loss nahi hota.

Example:

int quantity = 100;
double totalPrice = quantity;  // Automatic conversion int to double
System.out.println("Total price: " + totalPrice);  // Output: 100.0

Java me Type Promotion arithmetic operations ke dauran bhi hoti hai, jaise byte, short operands ko int me convert karna.

Widening vs Narrowing Casting

Type Description Example Safety
Widening Casting Chhota data type automatically bada data type me convert ho jata hai. int i = 10; long l = i; Safe, no data loss
Narrowing Casting Bada data type manually chhota data type me converted hota hai. double d = 9.99; int i = (int) d; Risk of data loss

Type Promotion in Expressions

Java arithmetic expressions me chhote types (byte, short, char) ko automatic int me promote karta hai jisse calculations accurately hoti hain. Agar koi operand bada (long, float, double) hota hai to promotions aur bhi logically apply hote hain.

byte b = 10;
short s = 20;
int result = b + s;  // b and s promoted to int before addition
System.out.println(result);  // 30

Common Errors & Tips

Summary

Type Casting aur Type Conversion dono hi jaruri concepts hain Java programming me, jinhone data types ke beech safe aur effective conversion possible banaya hai. Manual (explicit) aur automatic (implicit) conversions ka sahi gyaan efficient programming ke liye essential hai.