Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Check the object array instance of string array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Check the object array instance of string array" Watch "Check the object array instance of string array" New topic

Check the object array instance of string array

smitha rai
Ranch Hand

Joined: Aug 15, 2001
Posts: 33

I need to check the given object array is an instance of string array or not. Please refer to the following code. When the code is executed the control never goes into the if loop (if(objArray instanceof String[])). What am I missing here? Secondly when I try to cast the object array to a string array, I get class cast exception. Please help me out.



public class TestString {

public static void main(String[] args) {
String[] strArray = new String[] { "one", "two" };
Object[] objArray = new Object[] { "one1", "two2" };

System.out.println("From string array: " + (String) strArray.toString());
System.out.println("From object array: " + (String) objArray.toString());

if(objArray instanceof String[]) {
//Never enters into this loop
for(int i=0; i<objArray.length; i++) {
} else {
//Fails here - java.lang.ClassCastException: java.lang.Object
String[] strArray1 = (String[]) objArray;
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Hi Smitha,

First, a bit of business: seems you've been around here a long time! You're surely aware of our naming policy. It requires that you use a full, real (sounding) first and last name for your display name. You can change your display name here. Thanks!

Now, on to your problem: String[] is indeed subclass of Object[], so that, for example, this is OK:

Object[] myObjects = new String[] { "1", "2" };
String[] myStrings = (String[]) myObjects;

But note that the variable myObjects is pointing to something that was allocated as a String[], not as an Object[]. It's this last fact that makes the cast to String[] legal.

If, on the other hand, you allocate an Object[], then, even if it holds Strings, it's an array of Object, not an array of String, and it can't be cast to String[]. Likewise, whereas "myObjects instanceof String[]" is true using my definitions, "objArray instanceof String[]" is false in your program, because of the way objArray is allocated.

A cast of a reference type never changes the actual class of an object; it just gives the compiler more information than it presently has about the type a variable will be holding when the program runs.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Check the object array instance of string array
It's not a secret anymore!