L024 | Implicit and Explicit (TYPE CASTING) Type Conversion in Java
1. Introduction to Type Casting
- Definition: Type casting is the process of converting a variable from one data type to another.
- Purpose: It allows data conversion for compatibility between different types.
- Example: Converting an
int to a double for precise calculations.
2. Why is Type Casting Required?
- To perform operations between different data types.
- To store smaller data types in larger data types (automatic conversion).
- To convert larger data types into smaller ones (explicit conversion).
For example:
int num = 10;
double newNum = num; // Automatic widening
3. Types of Type Casting
Java provides two types of type casting:
| Type |
Description |
| Implicit Type Casting (Widening) |
Automatic conversion of a smaller type to a larger type. |
| Explicit Type Casting (Narrowing) |
Manual conversion of a larger type to a smaller type using type casting. |
4. Implicit Type Casting (Widening Conversion)
- Definition: Converts a smaller data type into a larger data type automatically.
- No data loss occurs.
- Happens automatically when storing a smaller type into a larger type.
Widening Conversions Supported in Java:
byte → short → int → long → float → double