File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Can we really downcast in Java - urgent  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can we really downcast in Java - urgent  " Watch "Can we really downcast in Java - urgent  " New topic
Author

Can we really downcast in Java - urgent

ms
Greenhorn

Joined: Oct 18, 2000
Posts: 10
Hi all ,
Can you please tell me that can we downcast in Java or it always throws the ClassCastException .
If it does can you please suggest the appropriate code for that .

Shall be extremely thankful !
Angela Poynton
Ranch Hand

Joined: Mar 02, 2000
Posts: 3143
A ClassCastException will only be thrown if you downcast an object to the wrong type (e.g. You have a String which is currently stored as type Object ... and you downcast it to an Integer by mistake.) ... I always downcast within a try/catch block and catch the exception .. just in case!
Almost always you will be sure what the actual type of the object is so the exception is very rarely thrown!

PS. We have a naming convention here at Javaranch can you please read this http://www.javaranch.com/name.jsp and re-register with an appropriate name.

[This message has been edited by Angela Poynton (edited March 20, 2001).]


Pounding at a thick stone wall won't move it, sometimes, you need to step back to see the way around.
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

Angela,
You do? I must just be egomaniac can do no wrong. Is that a common practice in the real world?

SCJP
Visit my download page
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
I don't think using an exception for this is a good idea. A much more common idiom, is to use instanceof:


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Neel D
Greenhorn

Joined: Mar 20, 2001
Posts: 2

Good Example Sheriff. Just happened to go thru this one.
Neel

[This message has been edited by Neel D (edited March 20, 2001).]
ms
Greenhorn

Joined: Oct 18, 2000
Posts: 10
Thanks a lot ! I am clear now .
Angela Poynton
Ranch Hand

Joined: Mar 02, 2000
Posts: 3143
Actually I prefer Frank's method ... am going to change ... it'll have to be a 12 step programme.
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
ms,
Please change your name to be compliant with JavaRanch's naming policy.
Your ID should be 2 separate names with more than 1 letter each. We really want this to be a professional forum and would prefer that you use your REAL name.
Thanks,
Cindy

"JavaRanch, where the deer and the Certified play" - David O'Meara
 
 
subject: Can we really downcast in Java - urgent