sandy chauhan wrote:Actually I want to know why we need casting of reference variable and when to use it.??
When the compiler can't determine whether an instance is a certain type, such as whether the Object instance passed to the method IS-A String instance needed in the method, it will complain (ie. compiler error). If you, as the programmer know better, then you can override the compiler with an explicit cast. However, you better be right, otherwise, all you did is convert a compiler error to a run-time exception.
You can use a cast if you have a variable of a certain type, and you need to let the Java compiler treat it as a different type.
Suppose that you have a plain List (you're not using generics). The List contains objects, but it has no information on what objects it contains. The get() method on List returns an Object. You'll need to cast the object that you got from the List to be able to do things with it. Here's a code example.
Normally, you would use generics in this case, so you would not need to cast. But in older versions of Java (1.4 and older) generics did not exist, so you had to cast every time you got an element from a list.
Note that casting does not do any kind of conversion. If the object you're trying to cast is not compatible with the type you're casting it to, you'll get a ClassCastException at runtime - it's not going to automatically convert the object to the desired type (some people seem to think that casting automatically converts objects, but it doesn't).
All you're really doing, is telling the compiler "I have an object here and I'm telling you that it's of type X, so I want you to treat it as if it is of type X - don't complain about it".
The page Inheritance in Oracle's Java Tutorials also explains casting.