Java Type Casting
Java Type Casting (Type Conversion)
Type casting in Java is the process of converting a variable from one data type to another. There are two types of type casting:
✅ 1. Widening Casting (Automatic / Implicit Conversion)
Converts a smaller type → larger type automatically.
No data loss occurs.
| From | To |
|---|---|
| byte → short → int → long → float → double |
Example:
🚀 2. Narrowing Casting (Manual / Explicit Conversion)
Converts a larger type → smaller type manually.
May result in data loss.
Example:
🎯 Important Notes
-
Widening Casting is safe since Java handles it automatically.
-
Narrowing Casting may lose precision, especially with decimals.
Additional Example:
🎉 Summary Table
| Type | Type Casting | Automatic? | Risk |
|---|---|---|---|
| Widening | Small → Large | Yes | No |
| Narrowing | Large → Small | No | Yes (data loss) |
