| Author |
Arrays Help needed
|
Arun Arun Kumar
Greenhorn
Joined: Sep 03, 2011
Posts: 4
|
|
Hi,
Object[] objArray = new String[3];
objArray[0] = new String("One");
objArray [1] = new Object();
when i run the program i get
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Object
at Arays.MyArray.main(MyArray.java:27)
Can someone explain what "Object[] objArray = new String[3];" actually signifies,
why we are not getting compile time error at line 3?
Thanks,
Arun
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19230
|
|
Arun Arun Kumar wrote:Can someone explain what "Object[] objArray = new String[3];" actually signifies,
You are creating an array that can hold 3 String references, and assign it a reference of type Object[]. That's allowed because a String[] IS-A Object[].
why we are not getting compile time error at line 3?
Because the compiler doesn't know the Object[] reference actually refers to a String[] object. The reference type is Object[], and the compiler allows any Object reference to be an element of it. The JVM will complain at runtime though, because the JVM does know that the Object[] reference refers to a String[] object.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Arrays Help needed
|
|
|