You use a cast to tell the compiler: "I have an object of type X here, but I know better than you what it really is, so I want you to treat it as type Y and not complain".
That's exactly what's happening in your code. You know that the first element in the list is a String, but List.get(...) returns an Object. You use a cast to tell the compiler that it should assume that the object is a String. Likewise with the Dog and the Integer object.
Note that Java will still check at runtime if the object you're casting really is of the type you're casting it to. If it isn't, you'll get a ClassCastException.
@Jesper de Jong :you told that Java will still check at runtime if the object you're casting really is of the type you're casting it to. If it isn't, you'll get a ClassCastException.
but here myList.get(); method return object of type Object and it does not of a type of String or Dog,because Object class is not refering to any object.
then it should give exception.but why it is not return exception?
In line 2, you're putting a String object "Fred" in the list.
In line 5, you're getting the object out of the list again by calling get(0).
The return type of the method List.get() is Object, but the object that is in the list at position 0 is the String object that you put into it in line 2.
When the compiler encounters line 5, it doesn't know that the object you're getting out of the list is really a String object. The only thing the compiler knows at that point is that it's an Object, because that's the return type of the method List.get(). You know that it's a String, because you put a String object there yourself in line 2.
So, what you do in line 5 is cast the result of the list.get() call to String, to let the compiler know that you want it to treat the return value as a String.
When you run the program, you do not get an exception, because the object at position 0 is indeed a String object.
Suppose you would change line 5 to this:
If you would run the program now, you would get a ClassCastException, because the object at position 1 in the list is not a String, but a Dog object (that you added to the list in line 3).
In other words: When you do a cast, you tell the compiler not to check the types; but the type of the object will still be checked when you run the program. If it is wrong (for example the object is really a Dog and not a String), you get a ClassCastException.
I presume you don't plan to use such casts in real production code. A List is better used to contain one type of element (hence the <Foo>) and casting of any sort is error‑prone. Downcasting reference types is particularly error‑prone.
Let's get him boys! We'll make him read this tiny ad!
Devious Experiments for a Truly Passive Greenhouse!