Type casting is the process of converting a variable from one data type to another. This is especially useful when you're working with different numeric types or when dealing with inheritance in object-oriented programming.
There are two main types of type casting in Java:
1. Widening Casting (Implicit):
This happens automatically when converting a smaller type to a larger type size:
int myInt = 9;
double myDouble = myInt;
2. Narrowing Casting (Explicit):
This must be done manually when converting a larger type to a smaller type:
java :
double myDouble = 9.78;
int myInt = (int) myDouble;
3.Type casting also applies to objects in inheritance hierarchies:
java :
Animal a = new Dog(); // Upcasting (automatic)
Dog d = (Dog) a;
class Test{
public static void main(String args[]){
byte b;
int i=257;
double d=323.142;
System.out.println("In conversion of byte . ");
b=(byte)i;
System.out.println("convertion of double to int. ");
i=(int)d;
System.out.println(" d and i " +d+" "+i);
System.out.println("converstion of double byte to byte);
b=(byte)d;
System.out.println("d and b"+d+" "+b);
}
}