Showing posts with label ClassCastException. Show all posts
Showing posts with label ClassCastException. Show all posts

Saturday, 31 March 2012

instanceof operator in Java

The instanceof operator compares an object to a specified type. You can use it to test at run-time if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The syntax of the instanceof operator is
Object_reference instanceof ClassName/InterfaceName

The instanceof operation returns boolean value ,either true or false.

The instanceof returns true, if the object referred to by the variable on the left side of the operator passes the IS-A test for the class or interface type on the right side.
Even if the object being tested is not an actual instantiation of the class type on
the right side of the operator, instanceof will still return true if the object being
compared is assignment compatible with the type on the right.


At compile time it checks whether the type of reference variable on the left and the class or interface on the left are in the same inheritance hierarchy.Else compile-time error occurs.For example

Thursday, 29 March 2012

ClassCastException in Java

public class ClassCastException
extends RuntimeException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. i.e.Thrown when attempting to cast a reference variable to a type that fails the IS-A test.

Before discussing more about ClassCastException let us go through reference variable casting.

Reference Variable Casting

Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.The compatible data types means they should follow the following contracts.

1. Both the reference variables types should be in the same inheritance hierarchy.Else compile-time error occurs.
2. When attempting to cast a reference variable to a type that should pass the IS-A test.Else run-time error occurs ,i.e. throws ClassCastException.