Type Casting

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
Scroll to top