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 Casting Object[] to String[] Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Casting Object[] to String[]" Watch "Casting Object[] to String[]" New topic
Author

Casting Object[] to String[]

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 761

Why can't I cast an Object[] to String[] ?


Regards,

Pho
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Have you tried it with an explicit cast?


Rob
SCJP 1.4
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Pho Tek:
Why can't I cast an Object[] to String[] ?

How did you try? Can you show us some code? What is the Object[] containing?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by Ilja Preuss:

How did you try? Can you show us some code? What is the Object[] containing?

Doesn't that type of casting cause a ClassCastException error at runtime if the Object is not actually a String object?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
It doesn't matter what the Object[] is containing - if it was created using new Object[], it really is an Object[] array even if all the elements are Strings. No Amount of casting can change this. However, if the array is really a String[] (created using new String[] for example) and you're just using a reference variable of type Object[] to refer to it, then you can cast. E.g.will compile OK, but will throw a ClassCastException at runtime because the array is not a String[] - just an Object[] containing Strings. However this works:
This illustrates why the cast in the previous example was allowed to succeed at compile time - a reference which is declared to be of type Object[] could hold a reference to a String[] (as it does in the second example). So the cast must be allowed at compile time - but it can still be invalid at run time.
This may seem strange, but it's nearly identical to the waycompiles but does not run, and compiles and runs.
[ May 30, 2002: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting Object[] to String[]