Type Casting

Type Casting

In this tutorial, we are going to discuss type casting in Java. Type casting is converting one data type into another one. It is also called data conversion or type conversion.General syntax of typecasting

Type Casting in java
Compile time checking 1

There should be some relationship between the type of ‘d’ and ‘c’. Otherwise, we will get a compile-time error saying inconvertible 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 incompatible 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(“Ashok”);
String s = (String)o; // Fine

Because internal Object type of o is String , so ‘c’(String), ‘d’(String) are same.

Consider following figure

Type Casting
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

That’s all about Type Casting in Java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!

Type Casting
Scroll to top