Type Casting
Typecasting is converting one data type into another one. It is also called as data conversion or type conversion.
General syntax of typecasting

Compile time checking 1
There should be some relation ship between the type of βdβ and βcβ. other wise we will get compile time error saying inconvertable types.
found : d required : c
E.g
String s = βAshokβ; Object o = (Object)s; // Fine
Because Object is parent to String.
String s = βAshokβ; Object o =(StringBuffer)s; // C.E inconvertible types
Compile time checking 2
βcβ must be same or derived type of βAβ other wise compile time error. Saying incompatable types
found : c required : A
E.g
String s = βAshokβ; Object o = (String)s;
Because String is child of Object.
String s = βAshokβ; StringBuffer sb = (Object)s; // C.E inconvertible types
Runtime Checking
The internal object type of βdβ must be same or derived type of βcβ other wise we will get RuntimeException saying
ClassCastException : βdβ type
E.g
Object o = new String(βAshokβ) ; StringBuffer sb = (StringBuffer)o; //C.E java.lang.ClassCastException
Object o = new String(βrajuβ); String s = (String)o; // Fine
Because internal Object type of o is String , so βcβ(String), βdβ(String) are same.
Consider following figure

Base ob1 = new Derived2(); //Fine Object ob2 = (Base)ob1; // Fine Derived2 ob3 = (Derived2)ob2; // Fine Base ob4 = (Derived2)ob3; // Fine Derived2 ob5 = (Derived1)ob4; //R.E ClassCastException
Type Casting