Java Topic
Type Casting
Type casting in Java is the process of converting one data type into another. It's essential for manipulating data effectively and performing various operations.
There are two primary types of type casting:
1. Widening (Implicit) Type Casting
- Converts a smaller data type to a larger one.
- No explicit cast operator is required.
- Safe operation as there's no loss of data.
Syntax:
(targetType) value
Example:
int num = 10;
double d = num; // Implicit casting from int to double
2. Narrowing (Explicit) Type Casting
- Converts a larger data type to a smaller one.
- Requires an explicit cast operator ( (target_type) ).
- Potential for data loss, so use with caution.
Example:
double d = 3.14;
int num = (int) d; // Explicit casting from double to int (data loss)

Primitive Type Casting
Java supports primitive data types like int, float, double, etc. Casting between these types follows the widening and narrowing rules mentioned above.
Object Type Casting
When dealing with objects, casting involves converting an object of one type to another.
Upcasting
- Converting a subclass object to a superclass reference.
- Safe operation as a subclass is a specialized version of its superclass.
- Implicitly done by the compiler.
Example:
class Animal { }
class Dog extends Animal { }
Dog d = class="keyword">new Dog();
Animal a = d; // Upcasting
Downcasting
- Converting a superclass reference to a subclass object.
- Requires an explicit cast operator.
- Potential for ClassCastException if the object is not actually of the specified subclass.
- Use instanceof operator to check the object's type before downcasting.
Example:
Dog d = new Dog(); // Upcasting
Dog d = (Dog) a; // Downcasting
if (a instanceof Dog) {
Dog d = (Dog) a; // Safe downcasting
} else {
// Handle the case where a is not a Dog
}
In short:
- Automatic Boxing/Unboxing:Java automatically converts between primitive types and their corresponding wrapper classes (like Integer, Double) in certain contexts.
- Generic Type Casting: Java generics allow type parameters to be used as placeholders for object types, providing type safety.Casting in Arrays: You can cast arrays to different types, but it's generally not recommended due to potential runtime errors.
Comments (0)
No comments yet. Be the first to comment!