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 


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 


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


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