Type casting in Java is the process of converting a variable from one data type to another. Java supports two types of casting: implicit (automatic) casting and explicit casting.
int intValue = 100;
long longValue = intValue; // Implicit casting from int to long
In the example above, the `intValue` of type `int` is implicitly cast to `long` without any explicit action from the programmer. This is possible because `long` can hold a larger range of values compared to `int`.
double doubleValue = 10.5;
int intValue = (int) doubleValue; // Explicit casting from double to int.
In the example above, `doubleValue`, a `double` variable, is explicitly cast to `int`. The decimal part is truncated during the conversion, and the `intValue` will hold the value `10`.
class Animal { … }
class Dog extends Animal { … }
Animal animal = new Dog(); // Upcasting (implicitly)
Dog dog = (Dog) animal; // Downcasting (explicitly)
Upcasting (implicit) :- Upcasting is safe and happens implicitly when you assign an instance of a subclass to a reference variable of its superclass.
Downcasting (explicit) :- Downcasting requires explicit casting when you want to treat an object of the superclass as an object of its subclass. It should be used with caution and is subject to the possibility of `ClassCastException` if the object being referred to is not actually an instance of the subclass.
int intValue = 42;
Integer integerValue = intValue; // Autoboxing (implicit)
int intValueAgain = integerValue; // Unboxing (implicit)
double doubleValue = 3.14;
Double doubleWrapper = doubleValue; // Autoboxing (implicit)
double doubleValueAgain = doubleWrapper; // Unboxing (implicit)
Autoboxing :- Implicit casting of a primitive data type to its corresponding wrapper class.
Unboxing :- Implicit casting of a wrapper class object to its primitive data type.
Remember :- that casting should be used carefully, especially explicit casting (narrowing casting), as it may lead to loss of data and potential errors. It’s essential to understand the ranges of data types and the potential implications of casting before using it in your Java code.