Introduce Java Type Casting and give examples
Java type casting is the process of converting a variable from one data type to another. This is particularly useful when you want to perform operations on different data types or when you want to store a value of one type in a variable of another type. There are two main types of type casting in Java: implicit casting (also known as widening) and explicit casting (also known as narrowing).
Implicit casting occurs when you convert a smaller data type to a larger data type. This is done automatically by the Java compiler because there is no risk of data loss. For example, converting an int
to a long
or a float
to a double
.
Example:
public class ImplicitCastingExample {
public static void main(String[] args) {
int intValue = 100;
long longValue = intValue; // Implicit casting from int to long
double doubleValue = longValue; // Implicit casting from long to double
System.out.println("Integer Value: " + intValue);
System.out.println("Long Value: " + longValue);
System.out.println("Double Value: " + doubleValue);
}
}
Explicit casting is required when you convert a larger data type to a smaller data type. This type of casting must be done manually because it can lead to data loss. For example, converting a double
to an int
.
Example:
public class ExplicitCastingExample {
public static void main(String[] args) {
double doubleValue = 9.78;
int intValue = (int) doubleValue; // Explicit casting from double to int
System.out.println("Double Value: " + doubleValue);
System.out.println("Integer Value after casting: " + intValue);
}
}
In addition to primitive types, type casting can also be applied to objects, particularly when dealing with inheritance. You can cast an object of a subclass to its superclass and vice versa.
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 ObjectCastingExample {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting (implicit)
myAnimal.sound(); // Calls the Dog's sound method
Dog myDog = (Dog) myAnimal; // Downcasting (explicit)
myDog.sound(); // Calls the Dog's sound method
}
}
int
to long
).double
to int
).Type casting is a powerful feature in Java that allows for flexibility in handling different data types, but it should be used carefully to avoid data loss and ClassCastException
errors.