File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Head First Java pg. 212" Watch "Head First Java pg. 212" New topic

Head First Java pg. 212

Leo Dorsman

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

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:
subject: Head First Java pg. 212
It's not a secret anymore!