This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Head First Java pg. 212 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Head First Java pg. 212" Watch "Head First Java pg. 212" New topic
Author

Head First Java pg. 212

Leo Dorsman
Greenhorn

Joined: Jul 31, 2003
Posts: 1
Based on the code i found on page 202 i did the following:

When i compile/run this it produces the following error.

When i uncomment lines 32 and 34 to enable the check like this:

then the code at line 33 does not generate the error (but is still illegal, right)?
Does anyone know what is going on ???
(I use Java SDK 1.4.2).
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

A ClassCastException is a runtime Exception. Since the condition in your 'if' statement evaluates to false, the program doesn't make it inside the subsequent block. The cast is never attempted, therefore, no error.
Hope this helps!
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Welcome to JavaRanch, Leo!
In your first example, you tried to get something out of TestList and turn it into something it's not. That commented out if statement checks to see if the thing coming out of the TestList is of the right data type before casting it to that data type, that's why the error doesn't occur when the if statement is not commented out.
The lesson here should perhaps be, if you have a reference to a Fish object, you cannot cast it into a reference of type Dog (unless the Fish object was actually a Dogfish, of course).
(Hey! I don't recall seeing a promise of quality humor 'round these parts - just being friendly to Greenhorns is all.)


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Head First Java pg. 212
 
Similar Threads
PA #1.....picture association
Changing the font size in java GUI
Dog in king seat
clone and java.io.File
Giving path alias to network folder in server.xml