When working with data in Java, you often need to convert one data type into another. This process is called Type Casting. It allows programmers to use variables in different contexts and ensures smooth execution of operations between different data types.
In this article, we’ll explore what type casting is, its types, and examples to make it easier to understand.
๐น What is Type Casting in Java?
Type casting in Java is the process of converting a variable of one data type into another. It is mainly used when we want to perform operations between different data types or when memory optimization is needed.
For example:
int num = 10;
double result = num; // int is converted to double
Here, the integer num is automatically converted into a double.
๐น Types of Type Casting in Java
Java supports two types of type casting:
1. Widening Casting (Implicit Casting / Type Promotion)
-
Automatically performed by Java.
-
Smaller data type is converted into a larger data type.
-
No data loss occurs.
Conversion order (small → large):
byte → short → int → long → float → double
Example:
public class WideningExample {
public static void main(String[] args) {
int num = 100;
double d = num; // int to double
System.out.println("Integer value: " + num);
System.out.println("Double value: " + d);
}
}
Output:
Integer value: 100
Double value: 100.0
2. Narrowing Casting (Explicit Casting)
-
Done manually by the programmer.
-
Larger data type is converted into a smaller data type.
-
May lead to data loss or precision loss.
Syntax:
dataType variableName = (dataType) value;
Example:
public class NarrowingExample {
public static void main(String[] args) {
double d = 9.78;
int num = (int) d; // double to int
System.out.println("Double value: " + d);
System.out.println("Integer value: " + num);
}
}
Output:
Double value: 9.78
Integer value: 9
๐น Type Casting with Non-Primitive Types
Apart from primitive data types, Java also allows type casting with objects and classes.
-
Upcasting: Casting a child object to a parent class (done automatically).
-
Downcasting: Casting a parent object to a child class (needs explicit casting).
Example:
class Animal {
void sound() { System.out.println("Animal makes a sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
public class CastingExample {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound();
Dog d = (Dog) a; // Downcasting
d.sound();
}
}
Output:
Dog barks
Dog barks
๐น Key Points to Remember
-
Widening casting is safe and done automatically.
-
Narrowing casting must be done manually and may cause data loss.
-
Object type casting is common in inheritance and polymorphism.
✅ Conclusion
Type casting in Java is an important concept that ensures flexibility while working with different data types and classes. By mastering both primitive type casting and object type casting, you can write efficient and error-free Java programs.
Comments
Post a Comment