Java Type Casting – Complete Guide with Examples and Rules
Learn everything about Java type casting, including implicit (widening), explicit (narrowing) conversion, type promotion, and best practices with examples.
Type Casting in Java – Complete Detailed Tutorial
In Java, type casting is the process of converting a variable from one data type to another.
It allows compatibility between different data types in expressions, assignments, or method calls.
1. Why Type Casting is Needed
- To assign values of one type to another type
- To perform operations on variables of different types
- To prevent data loss or enable precision conversion
Example:
2. Types of Type Casting in Java
Java supports two main types of type casting:
- Implicit Casting (Widening)
- Explicit Casting (Narrowing)
2.1 Implicit Casting (Widening Conversion)
- Automatic conversion by the compiler
- Converts smaller data type → larger data type
- Safe, no data loss
- Works for byte → short → int → long → float → double
Example:
Explanation:
intcan fit intodoublesafely → no explicit cast required
Another Example:
2.2 Explicit Casting (Narrowing Conversion)
- Manual conversion by the programmer
- Converts larger data type → smaller data type
- May lead to data loss
- Syntax:
(targetType) value
Example:
Another Example:
3. Type Casting Between Primitive Types
| From → ToImplicitExplicit | ||
| byte → short | ✅ | N/A |
| short → int | ✅ | N/A |
| int → long | ✅ | N/A |
| long → int | ❌ | ✅ (int) |
| float → double | ✅ | N/A |
| double → float | ❌ | ✅ (float) |
| char → int | ✅ | N/A |
| int → char | ❌ | ✅ (char) |
4. Type Casting Between Reference Types
- Can cast objects of classes within the same hierarchy
- Use upcasting and downcasting
4.1 Upcasting (Implicit)
- Child → Parent
- Safe and automatic
4.2 Downcasting (Explicit)
- Parent → Child
- Must be done explicitly, may throw ClassCastException
5. Type Promotion in Expressions
- Smaller types are automatically promoted in expressions
- Example:
6. Example Program – Type Casting
Output:
7. Summary
- Type casting converts variables from one type → another
- Implicit/Widening: smaller → larger, automatic, safe
- Explicit/Narrowing: larger → smaller, manual, may lose data
- Reference type casting: upcasting (safe), downcasting (requires explicit)
- Type promotion occurs in expressions to avoid data loss