β˜• Java Type Casting β€” Complete Deep Revision Guide

πŸ“– Type Casting Kya Hai?

Ek data type ki value ko doosre data type mein convert karna.

int a = 100;
double b = a;  ← int ko double mein daal diya = TYPE CASTING

Memory mein sizes:

byte(1) β†’ short(2) β†’ int(4) β†’ long(8) β†’ float(4) β†’ double(8)
↑ CHOTA                                                                           BADA ↑

βœ… Widening (Implicit)

  • Chote se Bade mein
  • Automatic / Safe
  • byte β†’ short β†’ int β†’ long β†’ float β†’ double

❌ Narrowing (Explicit)

  • Bade se Chote mein
  • Manual / Risky
  • Data loss ho sakta hai

πŸ”΅ Topic 1: Widening (Implicit) Type Casting

Deep Explanation: Widening matlab chote container ki cheez bade container mein daalna β€” automatically hota hai, kuch likhna nahi padta.

πŸ₯› Glass (int) β†’ πŸͺ£ Bucket (double) β†’ automatically fit ho jaata hai

int x = 100;
double y = x;  ← compiler khud karta hai
               Java sochta hai: "int β†’ double safe hai, karo"

βœ… Safe β€” Data loss NAHI hoga (mostly)
βœ… Automatic β€” Implicit kehte hain isliye

byte(8bit) β†’ short(16bit) β†’ int(32bit) β†’ long(64bit) β†’ float(32bit) β†’ double(64bit)
πŸ“ Widening1.java
public class Widening1 {
    public static void main(String[] args) {

        byte   b = 10;
        short  s = b;   // byte β†’ short  (automatic)
        int    i = s;   // short β†’ int   (automatic)
        long   l = i;   // int β†’ long    (automatic)
        float  f = l;   // long β†’ float  (automatic)
        double d = f;   // float β†’ double (automatic)

        System.out.println("byte   value: " + b);
        System.out.println("short  value: " + s);
        System.out.println("int    value: " + i);
        System.out.println("long   value: " + l);
        System.out.println("float  value: " + f);
        System.out.println("double value: " + d);
    }
}
β–Ά OUTPUT
byte value: 10
short value: 10
int value: 10
long value: 10
float value: 10.0
double value: 10.0
πŸ’‘ Short Explain: Ek hi value 10 ko har baar bade type mein daala β€” koi casting manually nahi likhi, Java ne khud kiya.
πŸ“ Widening2.java
public class Widening2 {
    public static void main(String[] args) {

        int    marks      = 95;
        double percentage = marks; // int β†’ double automatic

        System.out.println("Marks (int):         " + marks);
        System.out.println("Percentage (double): " + percentage);

        int a    = 10;
        int bVal = 3;
        double result  = a / bVal;           // ❌ pehle int/int = 3, phir 3.0
        double result2 = (double) a / bVal;  // βœ… sahi tarika

        System.out.println("Wrong division:   " + result);   // 3.0
        System.out.println("Correct division: " + result2);  // 3.3333
    }
}
β–Ά OUTPUT
Marks (int): 95
Percentage (double): 95.0
Wrong division: 3.0
Correct division: 3.3333333333333335
πŸ’‘ Division mein dhyan rakho β€” int/int pehle integer division hoti hai phir widen hota hai. Sahi result ke liye pehle cast karo.
πŸ“ Widening3.java
public class Widening3 {
    public static void main(String[] args) {

        // char β†’ int widening (char ka ASCII value milta hai)
        char ch    = 'A';
        int  ascii = ch;   // char β†’ int automatic, 'A' ka ASCII = 65

        System.out.println("char value:  " + ch);
        System.out.println("int  value:  " + ascii);   // 65

        char ch2    = 'a';
        int  ascii2 = ch2;
        System.out.println("char value:  " + ch2);
        System.out.println("int  value:  " + ascii2);  // 97

        // char β†’ double bhi possible
        double d = ch;
        System.out.println("double value: " + d);       // 65.0
    }
}
β–Ά OUTPUT
char value: A
int value: 65
char value: a
int value: 97
double value: 65.0
πŸ’‘ char se int mein widening hone par ASCII value milti hai. 'A' = 65, 'a' = 97, '0' = 48.
πŸ“ Widening4.java
public class Widening4 {
    public static void main(String[] args) {

        int price = 500;
        printPrice(price);        // int diya, double maanga β†’ auto widening

        long bigNumber = 1234567890L;
        printPrice(bigNumber);    // long diya β†’ auto widening
    }

    // method double leta hai
    static void printPrice(double amount) {
        System.out.println("Price: Rs." + amount);
    }
}
β–Ά OUTPUT
Price: Rs.500.0
Price: Rs.1.23456789E9
πŸ’‘ Method ko double chahiye tha, humne int diya β€” Java ne automatically widen kar diya. Yahi real-world widening use case hai.
πŸ“ Widening5.java
public class Widening5 {
    public static void main(String[] args) {

        // Widening mein data loss NAHI hota (mostly)
        int  x = 2147483647;   // int ka max value
        long y = x;             // safe - long mein fit ho jaayega

        System.out.println("int  max: " + x);
        System.out.println("long val: " + y);

        // int β†’ float mein THODA precision loss ho sakta hai
        int   bigInt = 123456789;
        float f      = bigInt;   // widening but float mein precision kam hai

        System.out.println("int   val: " + bigInt);
        System.out.println("float val: " + f);    // thoda different!
    }
}
β–Ά OUTPUT
int max: 2147483647
long val: 2147483647
int val: 123456789
float val: 1.23456792E8
πŸ’‘ int β†’ long mein data loss zero. But int β†’ float mein float ki precision limit hoti hai toh thoda change ho sakta hai.

πŸ”΄ Topic 2: Narrowing (Explicit) Type Casting

Deep Explanation: Narrowing matlab bade container ki cheez chote container mein daalna β€” manually karna padta hai.

πŸͺ£ Bucket (double) β†’ πŸ₯› Glass (int) β†’ manually karna padta hai, glass overflow ho sakta hai!

double d = 9.99;
int    i = (int) d;  ← (int) likhna padta hai explicitly

⚠️ Data Loss: double 9.99 β†’ int 9 (.99 chala gaya! truncation)
⚠️ Overflow: int 300 β†’ byte ? (byte max 127 hai, 300 fit nahi hoga!)

πŸ“ Narrowing1.java
public class Narrowing1 {
    public static void main(String[] args) {

        double d = 9.99;
        int    i = (int) d;   // ← explicit cast zaroori hai
        // decimal part CHALA JAATA hai (truncation, rounding nahi!)

        System.out.println("double value: " + d);  // 9.99
        System.out.println("int    value: " + i);  // 9 (not 10!)

        double d2 = 3.1;
        int    i2 = (int) d2;
        System.out.println("double value: " + d2); // 3.1
        System.out.println("int    value: " + i2); // 3
    }
}
β–Ά OUTPUT
double value: 9.99
int value: 9
double value: 3.1
int value: 3
πŸ’‘ 9.99 β†’ 9 β€” decimal part cut ho gaya, rounding NAHI hoti, sirf truncation (kaat do) hoti hai. Yeh data loss hai.
πŸ“ Narrowing2.java
public class Narrowing2 {
    public static void main(String[] args) {

        // int β†’ byte: byte ka range -128 to 127
        int  i1 = 100;
        byte b1 = (byte) i1;   // 100 fits in byte
        System.out.println("int 100 β†’ byte: " + b1);   // 100

        int  i2 = 130;
        byte b2 = (byte) i2;   // 130 > 127, overflow hoga!
        System.out.println("int 130 β†’ byte: " + b2);   // -126 (unexpected!)

        int  i3 = 256;
        byte b3 = (byte) i3;
        System.out.println("int 256 β†’ byte: " + b3);   // 0 (256 % 256 = 0)

        int  i4 = 257;
        byte b4 = (byte) i4;
        System.out.println("int 257 β†’ byte: " + b4);   // 1
    }
}
β–Ά OUTPUT
int 100 β†’ byte: 100
int 130 β†’ byte: -126
int 256 β†’ byte: 0
int 257 β†’ byte: 1
πŸ’‘ 130 β†’ -126 β€” yeh overflow hai! Jab value range se bahar ho toh unexpected result aata hai. Isliye narrowing "risky" hai.
πŸ“ Narrowing3.java
public class Narrowing3 {
    public static void main(String[] args) {

        // long β†’ int β†’ short β†’ byte chain
        long  l = 1000L;
        int   i = (int)   l;   // long β†’ int
        short s = (short) i;   // int β†’ short
        byte  b = (byte)  s;   // short β†’ byte

        System.out.println("long  value: " + l);  // 1000
        System.out.println("int   value: " + i);  // 1000
        System.out.println("short value: " + s);  // 1000
        System.out.println("byte  value: " + b);  // -24 (overflow!)

        // float β†’ int
        float f         = 45.7f;
        int   fromFloat = (int) f;
        System.out.println("float " + f + " β†’ int: " + fromFloat); // 45
    }
}
β–Ά OUTPUT
long value: 1000
int value: 1000
short value: 1000
byte value: -24
float 45.7 β†’ int: 45
πŸ’‘ 1000 byte mein fit nahi hota (max 127), toh overflow. Narrowing chain mein har step pe loss possible hai.
πŸ“ Narrowing4.java
public class Narrowing4 {
    public static void main(String[] args) {

        // int β†’ char (ASCII se character)
        int  ascii = 65;
        char ch    = (char) ascii;   // 65 β†’ 'A'
        System.out.println("int 65 β†’ char: " + ch);   // A

        int  ascii2 = 97;
        char ch2    = (char) ascii2;  // 97 β†’ 'a'
        System.out.println("int 97 β†’ char: " + ch2);  // a

        // double β†’ int β†’ char chain
        double d = 66.9;
        int    i = (int)  d;          // 66.9 β†’ 66
        char   c = (char) i;          // 66 β†’ 'B'
        System.out.println("double 66.9 β†’ int: " + i + " β†’ char: " + c);
    }
}
β–Ά OUTPUT
int 65 β†’ char: A
int 97 β†’ char: a
double 66.9 β†’ int: 66 β†’ char: B
πŸ’‘ int β†’ char se ASCII number se character milta hai. Yeh narrowing ka ek useful case hai β€” ASCII table ke saath kaam karna.
πŸ“ Narrowing5.java
public class Narrowing5 {
    public static void main(String[] args) {

        // Real world example - temperature convert
        double tempCelsius = 36.6;
        int    tempRounded = (int) tempCelsius;   // decimal cut
        System.out.println("Exact Temp:   " + tempCelsius + "Β°C");
        System.out.println("Rounded Temp: " + tempRounded + "Β°C");

        // Price calculation
        double totalBill = 1599.99;
        int    billInt   = (int) totalBill;
        System.out.println("Exact Bill: Rs." + totalBill);
        System.out.println("Truncated:  Rs." + billInt);

        // Safe narrowing - check karo pehle
        double safeVal = 50.5;
        if (safeVal >= Byte.MIN_VALUE && safeVal <= Byte.MAX_VALUE) {
            byte safeByte = (byte) safeVal;
            System.out.println("Safe cast: " + safeByte);
        } else {
            System.out.println("Value out of byte range! Cannot cast safely.");
        }
    }
}
β–Ά OUTPUT
Exact Temp: 36.6Β°C
Rounded Temp: 36Β°C
Exact Bill: Rs.1599.99
Truncated: Rs.1599
Safe cast: 50
πŸ’‘ Real use case β€” temperature ya price ko int mein convert karna. Safe narrowing ke liye pehle range check karo.

🟑 Topic 3: char, byte, short ke beech casting

Special Rule β€” Bahut log miss karte hain! ⚠️

❌ byte  β†’ char  : implicit NAHI hoga (compile error)
❌ char  β†’ byte  : implicit NAHI hoga (compile error)
❌ short β†’ char  : implicit NAHI hoga (compile error)
❌ char  β†’ short : implicit NAHI hoga (compile error)

Kyun nahi hota?

byte  β†’ signed   (-128 to 127)
short β†’ signed   (-32768 to 32767)
char  β†’ unsigned (0 to 65535)  ← DIFFERENT! negative nahi hota

Signed aur Unsigned ke beech automatic conversion UNSAFE hai β€” isliye Java ne explicitly likhna zaroori kiya.

// Fix:
byte b = 65;
char c = (char) b;  // βœ… explicit cast likhna padega
πŸ“ CharByteCast1.java
public class CharByteCast1 {
    public static void main(String[] args) {

        // byte β†’ char: explicit cast zaroori
        byte b = 65;
        // char c = b;        // ❌ Compile Error!
        char c = (char) b;    // βœ… explicit cast
        System.out.println("byte 65 β†’ char: " + c);   // A

        // char β†’ byte: explicit cast zaroori
        char ch   = 'Z';
        // byte bVal = ch;    // ❌ Compile Error!
        byte bVal = (byte) ch;  // βœ… explicit cast
        System.out.println("char Z β†’ byte: " + bVal);  // 90
    }
}
β–Ά OUTPUT
byte 65 β†’ char: A
char Z β†’ byte: 90
πŸ’‘ byte aur char same size ke hain (almost) but different signs β€” byte negative ho sakta, char nahi. Isliye explicit cast must hai.
πŸ“ CharByteCast2.java
public class CharByteCast2 {
    public static void main(String[] args) {

        // short β†’ char: explicit zaroori
        short s = 72;
        // char c = s;        // ❌ Compile Error!
        char  c = (char) s;    // βœ…
        System.out.println("short 72 β†’ char: " + c);   // H

        // char β†’ short: explicit zaroori
        char  ch   = 'M';
        // short sVal = ch;   // ❌ Compile Error!
        short sVal = (short) ch;  // βœ…
        System.out.println("char M β†’ short: " + sVal);  // 77
    }
}
β–Ά OUTPUT
short 72 β†’ char: H
char M β†’ short: 77
πŸ’‘ short signed hai, char unsigned β€” dono 16-bit hain par different range. Isliye implicit casting blocked hai Java mein.
πŸ“ CharByteCast3.java
public class CharByteCast3 {
    public static void main(String[] args) {

        // char range: 0 to 65535
        char maxChar   = '\uFFFF';  // max char value
        int  charAsInt = maxChar;
        System.out.println("Max char as int: " + charAsInt);  // 65535

        // Negative byte β†’ char kya hoga?
        byte negByte   = -1;
        char fromNeg   = (char) negByte;  // explicit cast
        int  result    = fromNeg;
        System.out.println("byte -1 β†’ char β†’ int: " + result);  // 65535!
        // -1 ka binary = 11111111 11111111 β†’ char mein 65535 ban gaya
    }
}
β–Ά OUTPUT
Max char as int: 65535
byte -1 β†’ char β†’ int: 65535
πŸ’‘ Yahi problem hai! byte -1 ko char mein daalo toh 65535 ban jaata hai β€” negative value ka meaning change ho gaya. Isliye implicit casting unsafe hai.
πŸ“ CharByteCast4.java
public class CharByteCast4 {
    public static void main(String[] args) {

        // Saare conversions int ke through safe hote hain

        // char β†’ int β†’ byte (do step)
        char ch = 'A';         // 65
        int  i  = ch;          // char β†’ int : βœ… widening (OK)
        byte b  = (byte) i;   // int β†’ byte : explicit cast
        System.out.println("char A β†’ int: " + i + " β†’ byte: " + b);

        // byte β†’ int β†’ char (do step)
        byte b2 = 66;
        int  i2 = b2;           // byte β†’ int : βœ… widening (OK)
        char c2 = (char) i2;   // int β†’ char : explicit cast
        System.out.println("byte 66 β†’ int: " + i2 + " β†’ char: " + c2);

        // Direct path:
        byte b3 = 67;
        char c3 = (char) b3;   // bhi chalega explicit se
        System.out.println("Direct byte 67 β†’ char: " + c3);
    }
}
β–Ά OUTPUT
char A β†’ int: 65 β†’ byte: 65
byte 66 β†’ int: 66 β†’ char: B
Direct byte 67 β†’ char: C
πŸ’‘ Safe way β€” pehle int mein convert karo (widening), phir jahan chahiye cast karo. Ya direct explicit cast use karo.

🟒 Topic 4: Casting + Arithmetic Expressions

Deep Explanation: Expression mein casting bohot important hai β€” galat jagah cast karo toh galat answer aata hai.

// ❌ GALAT
int a = 5, b = 2;
double result = a / b;           // pehle int/int = 2, phir 2.0

// βœ… SAHI
double result = (double) a / b;  // pehle 5.0/2, phir 2.5

⚠️ Rule: Cast jo pehle hoti hai woh calculation ko affect karti hai.

πŸ“ CastArithmetic1.java
public class CastArithmetic1 {
    public static void main(String[] args) {

        int a = 7, b = 2;

        // ❌ Wrong - int division pehle hoti hai
        double wrong = a / b;
        System.out.println("Wrong:    " + wrong);   // 3.0

        // βœ… Correct - pehle cast karo
        double correct = (double) a / b;
        System.out.println("Correct:  " + correct);  // 3.5

        // βœ… Dono cast karo
        double correct2 = (double) a / (double) b;
        System.out.println("Correct2: " + correct2); // 3.5
    }
}
β–Ά OUTPUT
Wrong: 3.0
Correct: 3.5
Correct2: 3.5
πŸ“ CastArithmetic2.java
public class CastArithmetic2 {
    public static void main(String[] args) {

        // Percentage calculate karna
        int scored = 450;
        int total  = 600;

        // ❌ Wrong way
        double wrongPercent = scored / total * 100;
        System.out.println("Wrong  %: " + wrongPercent);   // 0.0

        // βœ… Correct way
        double correctPercent = (double) scored / total * 100;
        System.out.println("Correct%: " + correctPercent);  // 75.0

        // Average
        int    s1  = 80, s2 = 90, s3 = 75;
        double avg = (double)(s1 + s2 + s3) / 3;
        System.out.println("Average: " + avg);               // 81.666...
    }
}
β–Ά OUTPUT
Wrong %: 0.0
Correct%: 75.0
Average: 81.66666666666667
πŸ’‘ Real world mein percentage/average calculate karte waqt (double) cast bhul gaye toh 0.0 ya wrong answer milega β€” yeh common mistake hai!

πŸ“‹ Complete Revision Summary

Type Direction How Risk
Widening Chota β†’ Bada
byte→short→int→long→float→double
Automatic / Implicit βœ… Safe (mostly)
Narrowing Bada β†’ Chota Manual β€” (type) likhna padta hai ⚠️ Data loss / Overflow
char/byte/short Inke beech koi bhi Explicit (type) MUST hai ⚠️ signed vs unsigned
Expression β€” (double)a/b βœ…   a/b wrong ❌ ⚠️ Wrong result

⚠️ Data Ranges

TypeSizeRange
byte1 byte-128 to 127
short2 bytes-32,768 to 32,767
int4 bytes-2.1B to 2.1B
long8 bytesvery large
float4 bytesdecimal (7 digits)
double8 bytesdecimal (15 digits)
char2 bytes0 to 65,535 (unsigned)

⚠️ Common Errors

ErrorReasonFix
possible lossy conversionBina cast ke narrowing(type) explicitly likho
incompatible typeschar↔byte/short without castExplicit (char) ya (byte) likho
Result 0.0 ya wrongint/int division(double) pehle cast karo
Overflow (-126 for 130)Value range se baharRange check karo pehle
πŸ† Golden Rule File name = Class name exactly! Jaise class Widening1 hai toh file Widening1.java hogi!
Java Type Casting - Complete Deep Revision Guide

β˜• Java Type Casting β€” Complete Deep Revision Guide

πŸ“– Type Casting Kya Hai?

Ek data type ki value ko doosre data type mein convert karna.

int a = 100;
double b = a;  ← int ko double mein daal diya = TYPE CASTING

Memory mein sizes:

byte(1) β†’ short(2) β†’ int(4) β†’ long(8) β†’ float(4) β†’ double(8)
↑ CHOTA                                                                           BADA ↑

βœ… Widening (Implicit)

  • Chote se Bade mein
  • Automatic / Safe
  • byte β†’ short β†’ int β†’ long β†’ float β†’ double

❌ Narrowing (Explicit)

  • Bade se Chote mein
  • Manual / Risky
  • Data loss ho sakta hai

πŸ”΅ Topic 1: Widening (Implicit) Type Casting

Deep Explanation: Widening matlab chote container ki cheez bade container mein daalna β€” automatically hota hai, kuch likhna nahi padta.

πŸ₯› Glass (int) β†’ πŸͺ£ Bucket (double) β†’ automatically fit ho jaata hai

int x = 100;
double y = x;  ← compiler khud karta hai
               Java sochta hai: "int β†’ double safe hai, karo"

βœ… Safe β€” Data loss NAHI hoga (mostly)
βœ… Automatic β€” Implicit kehte hain isliye

byte(8bit) β†’ short(16bit) β†’ int(32bit) β†’ long(64bit) β†’ float(32bit) β†’ double(64bit)
πŸ“ Widening1.java
public class Widening1 {
    public static void main(String[] args) {

        byte   b = 10;
        short  s = b;   // byte β†’ short  (automatic)
        int    i = s;   // short β†’ int   (automatic)
        long   l = i;   // int β†’ long    (automatic)
        float  f = l;   // long β†’ float  (automatic)
        double d = f;   // float β†’ double (automatic)

        System.out.println("byte   value: " + b);
        System.out.println("short  value: " + s);
        System.out.println("int    value: " + i);
        System.out.println("long   value: " + l);
        System.out.println("float  value: " + f);
        System.out.println("double value: " + d);
    }
}
β–Ά OUTPUT
byte value: 10
short value: 10
int value: 10
long value: 10
float value: 10.0
double value: 10.0
πŸ’‘ Short Explain: Ek hi value 10 ko har baar bade type mein daala β€” koi casting manually nahi likhi, Java ne khud kiya.
πŸ“ Widening2.java
public class Widening2 {
    public static void main(String[] args) {

        int    marks      = 95;
        double percentage = marks; // int β†’ double automatic

        System.out.println("Marks (int):         " + marks);
        System.out.println("Percentage (double): " + percentage);

        int a    = 10;
        int bVal = 3;
        double result  = a / bVal;           // ❌ pehle int/int = 3, phir 3.0
        double result2 = (double) a / bVal;  // βœ… sahi tarika

        System.out.println("Wrong division:   " + result);   // 3.0
        System.out.println("Correct division: " + result2);  // 3.3333
    }
}
β–Ά OUTPUT
Marks (int): 95
Percentage (double): 95.0
Wrong division: 3.0
Correct division: 3.3333333333333335
πŸ’‘ Division mein dhyan rakho β€” int/int pehle integer division hoti hai phir widen hota hai. Sahi result ke liye pehle cast karo.
πŸ“ Widening3.java
public class Widening3 {
    public static void main(String[] args) {

        // char β†’ int widening (char ka ASCII value milta hai)
        char ch    = 'A';
        int  ascii = ch;   // char β†’ int automatic, 'A' ka ASCII = 65

        System.out.println("char value:  " + ch);
        System.out.println("int  value:  " + ascii);   // 65

        char ch2    = 'a';
        int  ascii2 = ch2;
        System.out.println("char value:  " + ch2);
        System.out.println("int  value:  " + ascii2);  // 97

        // char β†’ double bhi possible
        double d = ch;
        System.out.println("double value: " + d);       // 65.0
    }
}
β–Ά OUTPUT
char value: A
int value: 65
char value: a
int value: 97
double value: 65.0
πŸ’‘ char se int mein widening hone par ASCII value milti hai. 'A' = 65, 'a' = 97, '0' = 48.
πŸ“ Widening4.java
public class Widening4 {
    public static void main(String[] args) {

        int price = 500;
        printPrice(price);        // int diya, double maanga β†’ auto widening

        long bigNumber = 1234567890L;
        printPrice(bigNumber);    // long diya β†’ auto widening
    }

    // method double leta hai
    static void printPrice(double amount) {
        System.out.println("Price: Rs." + amount);
    }
}
β–Ά OUTPUT
Price: Rs.500.0
Price: Rs.1.23456789E9
πŸ’‘ Method ko double chahiye tha, humne int diya β€” Java ne automatically widen kar diya. Yahi real-world widening use case hai.
πŸ“ Widening5.java
public class Widening5 {
    public static void main(String[] args) {

        // Widening mein data loss NAHI hota (mostly)
        int  x = 2147483647;   // int ka max value
        long y = x;             // safe - long mein fit ho jaayega

        System.out.println("int  max: " + x);
        System.out.println("long val: " + y);

        // int β†’ float mein THODA precision loss ho sakta hai
        int   bigInt = 123456789;
        float f      = bigInt;   // widening but float mein precision kam hai

        System.out.println("int   val: " + bigInt);
        System.out.println("float val: " + f);    // thoda different!
    }
}
β–Ά OUTPUT
int max: 2147483647
long val: 2147483647
int val: 123456789
float val: 1.23456792E8
πŸ’‘ int β†’ long mein data loss zero. But int β†’ float mein float ki precision limit hoti hai toh thoda change ho sakta hai.

πŸ”΄ Topic 2: Narrowing (Explicit) Type Casting

Deep Explanation: Narrowing matlab bade container ki cheez chote container mein daalna β€” manually karna padta hai.

πŸͺ£ Bucket (double) β†’ πŸ₯› Glass (int) β†’ manually karna padta hai, glass overflow ho sakta hai!

double d = 9.99;
int    i = (int) d;  ← (int) likhna padta hai explicitly

⚠️ Data Loss: double 9.99 β†’ int 9 (.99 chala gaya! truncation)
⚠️ Overflow: int 300 β†’ byte ? (byte max 127 hai, 300 fit nahi hoga!)

πŸ“ Narrowing1.java
public class Narrowing1 {
    public static void main(String[] args) {

        double d = 9.99;
        int    i = (int) d;   // ← explicit cast zaroori hai
        // decimal part CHALA JAATA hai (truncation, rounding nahi!)

        System.out.println("double value: " + d);  // 9.99
        System.out.println("int    value: " + i);  // 9 (not 10!)

        double d2 = 3.1;
        int    i2 = (int) d2;
        System.out.println("double value: " + d2); // 3.1
        System.out.println("int    value: " + i2); // 3
    }
}
β–Ά OUTPUT
double value: 9.99
int value: 9
double value: 3.1
int value: 3
πŸ’‘ 9.99 β†’ 9 β€” decimal part cut ho gaya, rounding NAHI hoti, sirf truncation (kaat do) hoti hai. Yeh data loss hai.
πŸ“ Narrowing2.java
public class Narrowing2 {
    public static void main(String[] args) {

        // int β†’ byte: byte ka range -128 to 127
        int  i1 = 100;
        byte b1 = (byte) i1;   // 100 fits in byte
        System.out.println("int 100 β†’ byte: " + b1);   // 100

        int  i2 = 130;
        byte b2 = (byte) i2;   // 130 > 127, overflow hoga!
        System.out.println("int 130 β†’ byte: " + b2);   // -126 (unexpected!)

        int  i3 = 256;
        byte b3 = (byte) i3;
        System.out.println("int 256 β†’ byte: " + b3);   // 0 (256 % 256 = 0)

        int  i4 = 257;
        byte b4 = (byte) i4;
        System.out.println("int 257 β†’ byte: " + b4);   // 1
    }
}
β–Ά OUTPUT
int 100 β†’ byte: 100
int 130 β†’ byte: -126
int 256 β†’ byte: 0
int 257 β†’ byte: 1
πŸ’‘ 130 β†’ -126 β€” yeh overflow hai! Jab value range se bahar ho toh unexpected result aata hai. Isliye narrowing "risky" hai.
πŸ“ Narrowing3.java
public class Narrowing3 {
    public static void main(String[] args) {

        // long β†’ int β†’ short β†’ byte chain
        long  l = 1000L;
        int   i = (int)   l;   // long β†’ int
        short s = (short) i;   // int β†’ short
        byte  b = (byte)  s;   // short β†’ byte

        System.out.println("long  value: " + l);  // 1000
        System.out.println("int   value: " + i);  // 1000
        System.out.println("short value: " + s);  // 1000
        System.out.println("byte  value: " + b);  // -24 (overflow!)

        // float β†’ int
        float f         = 45.7f;
        int   fromFloat = (int) f;
        System.out.println("float " + f + " β†’ int: " + fromFloat); // 45
    }
}
β–Ά OUTPUT
long value: 1000
int value: 1000
short value: 1000
byte value: -24
float 45.7 β†’ int: 45
πŸ’‘ 1000 byte mein fit nahi hota (max 127), toh overflow. Narrowing chain mein har step pe loss possible hai.
πŸ“ Narrowing4.java
public class Narrowing4 {
    public static void main(String[] args) {

        // int β†’ char (ASCII se character)
        int  ascii = 65;
        char ch    = (char) ascii;   // 65 β†’ 'A'
        System.out.println("int 65 β†’ char: " + ch);   // A

        int  ascii2 = 97;
        char ch2    = (char) ascii2;  // 97 β†’ 'a'
        System.out.println("int 97 β†’ char: " + ch2);  // a

        // double β†’ int β†’ char chain
        double d = 66.9;
        int    i = (int)  d;          // 66.9 β†’ 66
        char   c = (char) i;          // 66 β†’ 'B'
        System.out.println("double 66.9 β†’ int: " + i + " β†’ char: " + c);
    }
}
β–Ά OUTPUT
int 65 β†’ char: A
int 97 β†’ char: a
double 66.9 β†’ int: 66 β†’ char: B
πŸ’‘ int β†’ char se ASCII number se character milta hai. Yeh narrowing ka ek useful case hai β€” ASCII table ke saath kaam karna.
πŸ“ Narrowing5.java
public class Narrowing5 {
    public static void main(String[] args) {

        // Real world example - temperature convert
        double tempCelsius = 36.6;
        int    tempRounded = (int) tempCelsius;   // decimal cut
        System.out.println("Exact Temp:   " + tempCelsius + "Β°C");
        System.out.println("Rounded Temp: " + tempRounded + "Β°C");

        // Price calculation
        double totalBill = 1599.99;
        int    billInt   = (int) totalBill;
        System.out.println("Exact Bill: Rs." + totalBill);
        System.out.println("Truncated:  Rs." + billInt);

        // Safe narrowing - check karo pehle
        double safeVal = 50.5;
        if (safeVal >= Byte.MIN_VALUE && safeVal <= Byte.MAX_VALUE) {
            byte safeByte = (byte) safeVal;
            System.out.println("Safe cast: " + safeByte);
        } else {
            System.out.println("Value out of byte range! Cannot cast safely.");
        }
    }
}
β–Ά OUTPUT
Exact Temp: 36.6Β°C
Rounded Temp: 36Β°C
Exact Bill: Rs.1599.99
Truncated: Rs.1599
Safe cast: 50
πŸ’‘ Real use case β€” temperature ya price ko int mein convert karna. Safe narrowing ke liye pehle range check karo.

🟑 Topic 3: char, byte, short ke beech casting

Special Rule β€” Bahut log miss karte hain! ⚠️

❌ byte  β†’ char  : implicit NAHI hoga (compile error)
❌ char  β†’ byte  : implicit NAHI hoga (compile error)
❌ short β†’ char  : implicit NAHI hoga (compile error)
❌ char  β†’ short : implicit NAHI hoga (compile error)

Kyun nahi hota?

byte  β†’ signed   (-128 to 127)
short β†’ signed   (-32768 to 32767)
char  β†’ unsigned (0 to 65535)  ← DIFFERENT! negative nahi hota

Signed aur Unsigned ke beech automatic conversion UNSAFE hai β€” isliye Java ne explicitly likhna zaroori kiya.

// Fix:
byte b = 65;
char c = (char) b;  // βœ… explicit cast likhna padega
πŸ“ CharByteCast1.java
public class CharByteCast1 {
    public static void main(String[] args) {

        // byte β†’ char: explicit cast zaroori
        byte b = 65;
        // char c = b;        // ❌ Compile Error!
        char c = (char) b;    // βœ… explicit cast
        System.out.println("byte 65 β†’ char: " + c);   // A

        // char β†’ byte: explicit cast zaroori
        char ch   = 'Z';
        // byte bVal = ch;    // ❌ Compile Error!
        byte bVal = (byte) ch;  // βœ… explicit cast
        System.out.println("char Z β†’ byte: " + bVal);  // 90
    }
}
β–Ά OUTPUT
byte 65 β†’ char: A
char Z β†’ byte: 90
πŸ’‘ byte aur char same size ke hain (almost) but different signs β€” byte negative ho sakta, char nahi. Isliye explicit cast must hai.
πŸ“ CharByteCast2.java
public class CharByteCast2 {
    public static void main(String[] args) {

        // short β†’ char: explicit zaroori
        short s = 72;
        // char c = s;        // ❌ Compile Error!
        char  c = (char) s;    // βœ…
        System.out.println("short 72 β†’ char: " + c);   // H

        // char β†’ short: explicit zaroori
        char  ch   = 'M';
        // short sVal = ch;   // ❌ Compile Error!
        short sVal = (short) ch;  // βœ…
        System.out.println("char M β†’ short: " + sVal);  // 77
    }
}
β–Ά OUTPUT
short 72 β†’ char: H
char M β†’ short: 77
πŸ’‘ short signed hai, char unsigned β€” dono 16-bit hain par different range. Isliye implicit casting blocked hai Java mein.
πŸ“ CharByteCast3.java
public class CharByteCast3 {
    public static void main(String[] args) {

        // char range: 0 to 65535
        char maxChar   = '\uFFFF';  // max char value
        int  charAsInt = maxChar;
        System.out.println("Max char as int: " + charAsInt);  // 65535

        // Negative byte β†’ char kya hoga?
        byte negByte   = -1;
        char fromNeg   = (char) negByte;  // explicit cast
        int  result    = fromNeg;
        System.out.println("byte -1 β†’ char β†’ int: " + result);  // 65535!
        // -1 ka binary = 11111111 11111111 β†’ char mein 65535 ban gaya
    }
}
β–Ά OUTPUT
Max char as int: 65535
byte -1 β†’ char β†’ int: 65535
πŸ’‘ Yahi problem hai! byte -1 ko char mein daalo toh 65535 ban jaata hai β€” negative value ka meaning change ho gaya. Isliye implicit casting unsafe hai.
πŸ“ CharByteCast4.java
public class CharByteCast4 {
    public static void main(String[] args) {

        // Saare conversions int ke through safe hote hain

        // char β†’ int β†’ byte (do step)
        char ch = 'A';         // 65
        int  i  = ch;          // char β†’ int : βœ… widening (OK)
        byte b  = (byte) i;   // int β†’ byte : explicit cast
        System.out.println("char A β†’ int: " + i + " β†’ byte: " + b);

        // byte β†’ int β†’ char (do step)
        byte b2 = 66;
        int  i2 = b2;           // byte β†’ int : βœ… widening (OK)
        char c2 = (char) i2;   // int β†’ char : explicit cast
        System.out.println("byte 66 β†’ int: " + i2 + " β†’ char: " + c2);

        // Direct path:
        byte b3 = 67;
        char c3 = (char) b3;   // bhi chalega explicit se
        System.out.println("Direct byte 67 β†’ char: " + c3);
    }
}
β–Ά OUTPUT
char A β†’ int: 65 β†’ byte: 65
byte 66 β†’ int: 66 β†’ char: B
Direct byte 67 β†’ char: C
πŸ’‘ Safe way β€” pehle int mein convert karo (widening), phir jahan chahiye cast karo. Ya direct explicit cast use karo.

🟒 Topic 4: Casting + Arithmetic Expressions

Deep Explanation: Expression mein casting bohot important hai β€” galat jagah cast karo toh galat answer aata hai.

// ❌ GALAT
int a = 5, b = 2;
double result = a / b;           // pehle int/int = 2, phir 2.0

// βœ… SAHI
double result = (double) a / b;  // pehle 5.0/2, phir 2.5

⚠️ Rule: Cast jo pehle hoti hai woh calculation ko affect karti hai.

πŸ“ CastArithmetic1.java
public class CastArithmetic1 {
    public static void main(String[] args) {

        int a = 7, b = 2;

        // ❌ Wrong - int division pehle hoti hai
        double wrong = a / b;
        System.out.println("Wrong:    " + wrong);   // 3.0

        // βœ… Correct - pehle cast karo
        double correct = (double) a / b;
        System.out.println("Correct:  " + correct);  // 3.5

        // βœ… Dono cast karo
        double correct2 = (double) a / (double) b;
        System.out.println("Correct2: " + correct2); // 3.5
    }
}
β–Ά OUTPUT
Wrong: 3.0
Correct: 3.5
Correct2: 3.5
πŸ“ CastArithmetic2.java
public class CastArithmetic2 {
    public static void main(String[] args) {

        // Percentage calculate karna
        int scored = 450;
        int total  = 600;

        // ❌ Wrong way
        double wrongPercent = scored / total * 100;
        System.out.println("Wrong  %: " + wrongPercent);   // 0.0

        // βœ… Correct way
        double correctPercent = (double) scored / total * 100;
        System.out.println("Correct%: " + correctPercent);  // 75.0

        // Average
        int    s1  = 80, s2 = 90, s3 = 75;
        double avg = (double)(s1 + s2 + s3) / 3;
        System.out.println("Average: " + avg);               // 81.666...
    }
}
β–Ά OUTPUT
Wrong %: 0.0
Correct%: 75.0
Average: 81.66666666666667
πŸ’‘ Real world mein percentage/average calculate karte waqt (double) cast bhul gaye toh 0.0 ya wrong answer milega β€” yeh common mistake hai!

πŸ“‹ Complete Revision Summary

Type Direction How Risk
Widening Chota β†’ Bada
byte→short→int→long→float→double
Automatic / Implicit βœ… Safe (mostly)
Narrowing Bada β†’ Chota Manual β€” (type) likhna padta hai ⚠️ Data loss / Overflow
char/byte/short Inke beech koi bhi Explicit (type) MUST hai ⚠️ signed vs unsigned
Expression β€” (double)a/b βœ…   a/b wrong ❌ ⚠️ Wrong result

⚠️ Data Ranges

TypeSizeRange
byte1 byte-128 to 127
short2 bytes-32,768 to 32,767
int4 bytes-2.1B to 2.1B
long8 bytesvery large
float4 bytesdecimal (7 digits)
double8 bytesdecimal (15 digits)
char2 bytes0 to 65,535 (unsigned)

⚠️ Common Errors

ErrorReasonFix
possible lossy conversionBina cast ke narrowing(type) explicitly likho
incompatible typeschar↔byte/short without castExplicit (char) ya (byte) likho
Result 0.0 ya wrongint/int division(double) pehle cast karo
Overflow (-126 for 130)Value range se baharRange check karo pehle
πŸ† Golden Rule File name = Class name exactly! Jaise class Widening1 hai toh file Widening1.java hogi!