This week's giveaway is in the Spring forum.
We're giving away four 3 month subscriptions to Marco Behler Videos and have Marco Behler on-line!
See this thread for details.
Win a 3 month subscription to Marco Behler Videos this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Check the object array instance of string array  RSS feed

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

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
Posts: 24217
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
Boost this thread!