Type Casting & Type Conversion in Java

🟢 Beginner Level | Java Core Syntax

📖 Definition

Type Casting is the process of converting a variable from one primitive data type to another. Java supports Widening Casting (implicit automatic conversion) and Narrowing Casting (explicit manual casting).

🌐 Multilingual Explanations

English

Widening casting converts smaller to larger data types automatically. Narrowing casting converts larger to smaller data types manually using (type) and can cause data truncation/overflow.

Hindi

Chote data type se bade data type mein automatic widening casting hoti hai. Bade se chote type mein manually narrowing casting `(int)` karni padti hai.

Marathi

Lahan type kadun mothya type kade automatic Widening casting hote. Mothya type kadun lahan type kade Narrowing casting saathi manual `(int)` vapra.

Hinglish

Widening = Safe automatic conversion (e.g., `int` -> `double`). Narrowing = Risky manual conversion with potential data loss (e.g., `(int) 9.99` becomes `9`).

📈 Type Conversion Hierarchy

Widening (Automatic):  byte ──► short ──► char ──► int ──► long ──► float ──► double
Narrowing (Manual):    double ──► float ──► long ──► int ──► char ──► short ──► byte

⚡ Code Example

public class TypeCastingDemo {
    public static void main(String[] args) {
        // 1. Widening Casting (Implicit)
        int myInt = 9;
        double myDouble = myInt; // Automatic casting: 9.0

        // 2. Narrowing Casting (Explicit)
        double pi = 3.14159;
        int intPi = (int) pi; // Manual casting: 3 (decimal truncated)

        // 3. ASCII Char to Int Conversion
        char letter = 'A';
        int asciiValue = letter; // Automatic conversion: 65

        System.out.println("intPi: " + intPi + ", ASCII: " + asciiValue);
    }
}

⚠️ Common Pitfalls

Integer Truncation & Overflow: Narrowing a float/double to an integer discards all decimal precision without rounding. Casting a number larger than `byte` max (127) to a `byte` causes binary wrap-around overflow.

🎯 Tiered Practice Exercises

  1. Beginner: Cast a double value 99.99 to an integer and print the result.
  2. Intermediate: Demonstrate character arithmetic by adding 1 to 'A' and printing the resulting character.
  3. Advanced: Explain what happens when a long value exceeding Integer.MAX_VALUE is cast to an int.

🧭 Navigation

← 01. Variables & Primitives | Module Hub | 03. Wrapper Classes →