Type casting in Java
✅ What is Type Casting?
Type Casting in Java is the process of converting a value from one data type to another.
Java has two types of type casting:
-
Widening (Implicit) Casting – small → large type
-
Narrowing (Explicit) Casting – large → small type
🔹 1. Widening Type Casting (Automatic)
Definition: Converting a smaller data type to a larger one.
👉 Safe conversion – done automatically by Java.
🔸 Example:
Output:
✅ Widening Order:
byte
→ short
→ int
→ long
→ float
→ double
🔹 2. Narrowing Type Casting (Manual)
Definition: Converting a larger data type to a smaller one.
👉 Not safe automatically, so explicit casting is required.
🔸 Example:
Output:
⚠️ Decimal part is lost during narrowing.
🔸 Example with Character
🔹 Summary Table
Type | Conversion Example | Casting Needed? |
---|---|---|
Widening | int → double | ❌ No |
Narrowing | double → int | ✅ Yes |
Char to Int | 'A' → 65 | ❌ No |
Int to Char | 65 → 'A' | ✅ Yes |
Comments
Post a Comment