This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check the object array instance of string array

 
smitha rai
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

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.

Thanks,

Smitha

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++) {
System.out.println(objArray[i]);
}
} else {
System.out.println("Failed");
}
//Fails here - java.lang.ClassCastException: java.lang.Object
String[] strArray1 = (String[]) objArray;
}
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic