Kenny
Kenny

Reputation: 1982

String array instance assigned to single Object

I came across this Java question: Which one of the following declaration is false:

a. Object[] myarr1 = new String[3];
b. Object myarr2 = new String[3];
c. String[] myarr3 = new String[3];
d. String myarr3[] = new String[3];

I thought it seems obvious that b is the answer. However, the declaration in b is actually correct upon my checking in Eclipse! Furthermore, I tried the following:

A. Object[] myarr1 = new String[]{"a1","b1","c1"};
B. Object myarr2 = new String[]{"a2","b2","c2"};
C. String[] myarr3 = new String[]{"a3","b3","c3"};

and printed out the content of each array to study what it actually means by assigning an Object to a String array.

System.out.println(myarr1[0]); //print "a1"
System.out.println(myarr2[0]); //error
System.out.println(myarr3[0]); //print "a3"
System.out.println(myarr1); //print address of myarr1
System.out.println(myarr2); //print address of myarr2
System.out.println(myarr3); //print address of myarr3

It seems myarr1 and myarr3 behave like ordinary String arrays, while myarr2 is different. Debugging to look into the content of myarr2 however showed that the content and structure of myarr2 seems to be the same as myarr1 and myarr3.

Can someone explain to me the significance of this? What are we doing when we use declaration b or B. What is the structure of myarr2 and how do I access its elements or cast it as if it is a String array? I tried (String[])myarr2 but that was an error.

Thanks to all.

Upvotes: 1

Views: 3461

Answers (2)

janos
janos

Reputation: 124656

They all compile, so they are all correct, as of Java 6.

b. Object myarr2 = new String[3];

This works, because everything you create with the new operator is an object in Java. You could later cast it back to its real type, for example these will work as expected:

Object myarr2 = new String[] { "first", "second" };
String[] real = (String[]) myarr2;
real[1] = "hello";
System.out.println(real[1]);                // will output "hello"
System.out.println(((String[])myarr2)[1]);  // will output "hello"

d. String myarr3[] = new String[3];

This is valid but discouraged as per this doc:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Upvotes: 1

arshajii
arshajii

Reputation: 129517

The reason your second print statement emits an error is because the compiler does not know what myarr2 actually is, it just knows it's an Object. For example, you could have had:

Object myarr2 = rand() ? new String[3] : new Dog();

i.e. myarr2 could be some other completely unrelated object as well.

Hence, you cannot index myarr2 as an array. Of course, this can be addressed with a cast:

System.out.println(((String[])myarr2)[0]);

Upvotes: 0

Related Questions